I have a login app that needs to connect to a server to check the username and password. I am using netbeans and the jbdc is installed and working in the services tab(thanks stack overflow!). By the jbdc is work I mean that i can execute SQL script through it.
I have set this up with MS Server 16 and MySQL so I am convied it is the code:
Connection method:
package dbUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class dbConnection {
private static final String USERNAME = "root";
private static final String PASSWORD = "mess";
private static final String SQCONN = "jdbc:mysql://localhost:1434/MessyLogin?zeroDateTimeBehavior=convertToNull";
public static Connection getConnection()throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(SQCONN, USERNAME, PASSWORD);
}catch (ClassNotFoundException e) {
}
return null;
}
}
loginmodel:
package LogIn;
import dbUtil.dbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogInModel {
Connection connection;
public LogInModel() {
try{
this.connection = dbConnection.getConnection();
}catch(SQLException e){
}
if(this.connection == null){
System.out.println("here");
// System.exit(1);
}
}
public boolean isDatabaseConnected(){
return this.connection != null;
}
public boolean isLogin(String username, String password) throws Exception{
PreparedStatement pr = null;
ResultSet rs = null;
String sql = "SELECT * FROM MessyLogin where username = ? and Password = ?";
try{
pr = this.connection.prepareStatement(sql);
pr.setString(1, username);
pr.setString(2, password);
rs = pr.executeQuery();
boolean bool1;
if(rs.next()){
return true;
}
return false;
}
catch(SQLException ex){
return false;
}
finally {
{
pr.close();
rs.close();
}
}
}
}
I believe the issue is the return null; from the dbConnection file. The if(this.connection==Null) comes back true and the system is exiting.
Thank you in advance.
Your dbConnection class is a bad idea. Why hard wire those values when you can pass them in?
Your application will only have one Connection if you code it this way. A more practical solution will use a connection pool.
Learn Java coding standards. Your code doesn't follow them; it makes it harder to read and understand.
Here's a couple of recommendations:
package dbUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class dbConnection {
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String USERNAME = "root";
public static final String PASSWORD = "mess";
public static final String URL = "jdbc:mysql://localhost:1434/MessyLogin?zeroDateTimeBehavior=convertToNull";
public static Connection getConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
}
I might write that LogInModel this way:
package LogIn;
import dbUtil.dbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogInModel {
private static final String sql = "SELECT * FROM MessyLogin where username = ? and Password = ?";
private Connection connection;
public LogInModel(Connection connection) {
this.connection = connection;
}
public boolean isLogin(String username, String password) {
boolean isValidUser = false;
PreparedStatement pr = null;
ResultSet rs = null;
try {
pr = this.connection.prepareStatement(sql);
pr.setString(1, username);
pr.setString(2, password);
rs = pr.executeQuery();
while (rs.hasNext()) {
isValidUser = true;
}
} catch (SQLException ex) {
e.printStackTrace();
isValidUser = false;
} finally {
dbUtils.close(rs);
dbUtils.close(pr);
}
return isValidUser;
}
}
Here's my guess as to why your code fails: You don't have the MySQL JDBC driver JAR in your runtime CLASSPATH. There's an exception thrown when it can't find the driver class, but you didn't know it because you swallowed the exception.
Related
I have linked up a database to my Java application using the JDBC in Netbeans.
But whenever I try to write something from a TextField to a MySQL table, it doesn't work.
I have a pre-made class to make the database connection.
Here is my database class:
package testswitch;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Maarten
*/
public class Database {
public final static String DB_DRIVER_URL = "com.mysql.jdbc.Driver";
public final static String DB_DRIVER_PREFIX = "jdbc:mysql://";
private Connection connection = null;
public Database(String dataBaseName, String serverURL, String userName, String passWord) {
try {
// verify that a proper JDBC driver has been installed and linked
if (!selectDriver(DB_DRIVER_URL)) {
return;
}
if (serverURL == null || serverURL.isEmpty()) {
serverURL = "localhost:3306";
}
// establish a connection to a named Database on a specified server
connection = DriverManager.getConnection(DB_DRIVER_PREFIX + serverURL + "/" + dataBaseName, userName, passWord);
} catch (SQLException eSQL) {
logException(eSQL);
}
}
private static boolean selectDriver(String driverName) {
// Selects proper loading of the named driver for Database connections.
// This is relevant if there are multiple drivers installed that match the JDBC type.
try {
Class.forName(driverName);
// Put all non-prefered drivers to the end, such that driver selection hits the first
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver d = drivers.nextElement();
if (!d.getClass().getName().equals(driverName)) {
// move the driver to the end of the list
DriverManager.deregisterDriver(d);
DriverManager.registerDriver(d);
}
}
} catch (ClassNotFoundException | SQLException ex) {
logException(ex);
return false;
}
return true;
}
public void executeNonQuery(String query) {
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(query);
} catch (SQLException eSQL) {
logException(eSQL);
}
}
public ResultSet executeQuery(String query) {
Statement statement;
try {
statement = connection.createStatement();
ResultSet result = statement.executeQuery(query);
return result;
} catch (SQLException eSQL) {
logException(eSQL);
}
return null;
}
private static void logException(Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
}
And here's my JavaFX controller.
What I want is that when the "handle" button is pressed, that the data filled in the TextField gets inserted into the database.
package testswitch;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import testswitch.Database;
/**
*
* #author Maarten
*/
public class gebruikerToevoegenController {
//TextFields
#FXML
private TextField FXVoornaam, FXTussenvoegsel, FXAchternaam, FXGebruikersnaam;
#FXML
private TextField FXWachtwoord, FXEmail, FXTelefoonnummer;
//Boolean checkbox positie
#FXML
private CheckBox ManagerPosition;
#FXML
private Button gebruikerButton;
public final String DB_NAME = "testDatabase";
public final String DB_SERVER = "localhost:3306";
public final String DB_ACCOUNT = "root";
public final String DB_PASSWORD = "root";
Database database = new Database(DB_NAME, DB_SERVER, DB_ACCOUNT, DB_PASSWORD);
public void handle(ActionEvent event) throws SQLException {
String query = "INSERT INTO testDatabase.Gebruikers (Voornaam) VALUES " + FXVoornaam.getText();
try {
database.executeQuery(query);
} catch (Exception e) {
}
}
}
Thanks in advance
The string in your SQL query doesn't seem to be properly quoted. It's best to use PreparedStatement for this scenario:
public class Database {
public PreparedStatement prepareStatement(String query) throws SQLException {
return connection.prepareStatement(query);
}
...
public void handle(ActionEvent event) throws SQLException {
String query = "INSERT INTO testDatabase.Gebruikers (Voornaam) VALUES (?);";
PreparedStatement statement = database.prepareStatement(query);
try {
statement.setString(1, FXVoornaam.getText());
statement.executeUpdate();
} catch (Exception e) {
// log info somewhere at least until it's properly tested/
// you implement a better way of handling the error
e.printStackTrace(System.err);
}
}
You have to add like this in JavaFx :
String query = "INSERT INTO testDatabase.Gebruikers (Voornaam) VALUES ('{FXVoornaam.getText()}') ";
String query = "INSERT INTO testDatabase.Gebruikers(Voornaam)
VALUES('" + FXVoornaam.getText() + "')";
i don't understand why my variable state cannot be resolved.
i'm in a java Mysql project.
Here is the Commands class code:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class Commands {
public Commands() throws SQLException{
Connection conn = DbConn.getInstance();
Statement state = conn.createStatement();
}
public String getList(){
System.out.println("Here is a List of our Products:");
// Get list from db
ResultSet result = state.executeQuery("SELECT * FROM products");
ResultSetMetaData resultMeta = result.getMetaData();
// Display the List
System.out.println("List displayed");
return null;
}
}
Here is the DbConn class code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConn {
private static String url = "jdbc:mysql://localhost:3306/myDB";
private static String user = "root";
private static String passwd = "";
private static Connection connect;
// create new instance if not exists
public static Connection getInstance(){
if(connect == null){
try {
connect = DriverManager.getConnection(url, user, passwd);
} catch (SQLException e) {
e.printStackTrace();
}
}
return connect;
}
}
My code is not finished yet, but the message come on this line:
ResultSet result = state.executeQuery("SELECT * FROM products");
My Eclipse editor says this message state cannot be resolved
Any idea?
That is a matter of scope. You define the variable here
public Commands() throws SQLException{
Connection conn = DbConn.getInstance();
Statement state = conn.createStatement();
}
And that is the only place the variable is visible - in the constructor. Define it in the class and initialize it in the constructor:
private Connection conn = null;
private Statement state = null;
public Commands() throws SQLException{
conn = DbConn.getInstance();
state = conn.createStatement();
}
Declare "State" outside of that constructor.
Connection conn = null;
Statement state = null;
public Commands() throws SQLException{
conn = DbConn.getInstance();
state = conn.createStatement();
}
I'm working on my application where I want to update my table after email has been sent. I created function that connect sql database and java, also in other class I created function that updates table but what I need is these two classes together. I want to use my array-list after execution for updating of my table.
Here is my code for connection and sending emails:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class TestSendEmails {
private String emailTo;
private String emailSubject;
private String emailBody;
private String emailAttachments;
private Integer RecordId;
public TestSendEmails(){
}
public TestSendEmails(String emailTo, String emailSubject, String emailBody, String emailAttachments, Integer RecordId){
super();
this.emailTo = emailTo;
this.emailSubject = emailSubject;
this.emailBody = emailBody;
this.emailAttachments = emailAttachments;
this.RecordId = RecordId;
}
public String getEmailTo(){
return emailTo;
}
public void setEmailTo(String emailTo){
this.emailTo = emailTo;
}
public String getEmailSubject(){
return emailSubject;
}
public void setEmailSubject(String emailSubject){
this.emailSubject = emailSubject;
}
public String getEmailBody(){
return emailBody;
}
public void setEmailBody(String emailBody){
this.emailBody = emailBody;
}
public String getEmailAttachments(){
return emailAttachments;
}
public void setEmailAttachments(String emailAttachments){
this.emailAttachments = emailAttachments;
}
public Integer getRecordId(){
return RecordId;
}
public void setRecordId(Integer RecordId){
this.RecordId = RecordId;
}
}
class TestSendEmailD{
private Connection con;
private static final String GET_EMAILS = "Select* From Emails";
private void connect() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
con = DriverManager.getConnection("jdbc:sqlserver://100.000.000.00\\:3333;databaseName=Test;user=mmmm;password=1234");
}
public List<TestSendEmails> getTestSendEmails() throws Exception{
connect();
PreparedStatement ps = con.prepareStatement(GET_EMAILS);
ResultSet rs = ps.executeQuery();
List<TestSendEmails> result = new ArrayList<TestSendEmails>();
while(rs.next()){
result.add(new TestSendEmails(rs.getString("emailTo"), rs.getString("emailSubject"),rs.getString("emailBody"),rs.getString("emailAttachments",rs.getInt("RecordId"))));
}
disconnect();
return result;
}
private void disconnect() throws SQLException{
if(con != null){
con.close();
}
}
}
class EmailSender{
private Session session;
private void init(){
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "100.000.000.00");
props.put("mail.smtp.port", "678");
session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("test#gmail.com", "123");
}
});
}
public void sendEmail(TestSendEmails s) throws MessagingException{
init();
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("test#gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(s.getEmailTo().replace(";", ",")));
message.setSubject(s.getEmailSubject());
message.setText(s.getEmailBody());
message.setContent(s.getEmailBody(),"text/html");
Transport.send(message);
System.out.println("Done");
}
public void sendEmail(List<TestSendEmails> emails) throws MessagingException{
for(TestSendEmails TestSendEmails:emails ){
sendEmail(TestSendEmails);
}
}
}
Here is my Update code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Date;
public class UpdateEmail {
public static Connection getConnection() throws Exception {
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://100.000.000.00\\:3333;databaseName=Test";
String username = "mmmm";
String password = "1234";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void main(String[] args) throws Exception {
java.util.Date date = new Date();
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "update Emails set SentOn = ? where Id = ? ";
pstmt = conn.prepareStatement(query); // create a statement
pstmt.setTimestamp(1, new java.sql.Timestamp(date.getTime()));
pstmt.setInt(2, 200); // In this line I want to use my array-list to update my table.
pstmt.executeUpdate(); // execute update statement
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
pstmt.close();
conn.close();
}
}
}
I'm not sure if I have to create new connection for my update in my second program and where I should implement my update code. If you know what I should change please let me know. Thanks in advance.
Main.java code:
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
TestSendEmailD dao=new TestSendEmailD();
List<TestSendEmails> list=dao.getTestSendEmails();
EmailSender sender=new EmailSender();
sender.sendEmail(list);
}
}
I guess you have an ArrayList() called yourList. The following code goes before
String query ...
StringBuilder ids = "";
String prefix ="";
for (Integer id: yourList) {
append(prefix);
prefix = ",";
ids.append(String.valueOf(id));
}
change your query to:
String query = "update Emails set SentOn =? where Id in (" + ids.toString() + ")";
and send only the SentOn as parameter:
pstmt.setTimestamp(1, new java.sql.Timestamp(date.getTime()));
Connection conn = null;
PreparedStatement pstmt = null;
conn = getConnection();
java.util.Date date = new Date();
message.setFrom(new InternetAddress("test#gmail.com"));
String query = "update Emails set SentOn = ? where Id = ? ";
pstmt = conn.prepareStatement(query); // create a statement
String str[]=String.valueOf(s.getRecordId()).split(";");//id1;id;id3;....
for(int i=0;i<str.length();i++)
{
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(s.getEmailTo().replace(";", ",")[i]));
message.setSubject(s.getEmailSubject());
message.setText(s.getEmailBody());
message.setContent(s.getEmailBody(),"text/html");
Transport.send(message);
System.out.println("Done");
pstmt.setTimestamp(1, new java.sql.Timestamp(date.getTime()));
pstmt.setInt(2, str[i]); // In this line I want to use my array-list to update my table.
pstmt.executeUpdate(); // execute update statement
System.out.println(str[i]+" "+s.getEmailTo().replace(";", ",")[i]+" "+new java.sql.Timestamp(date.getTime()));//to check whether its working or not.
}
Its exactly not an exact answer. check whether its working or not. Here you must take care of exceptions also. I didn't written that code here.
I'm working on web java application with OSGI. I get this error when I try to open JSF page: java.lang.reflect.UndeclaredThrowableException
This is the source code that I'm working on:
package org.DX_57.osgi.SH_27.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.DX_57.osgi.SH_27.api.SessionHandle;
public class SessionHandleImpl implements SessionHandle {
#Resource(name="jdbc/Oracle")
public DataSource ds;
public String sayHello(String name) {
return "Howdy " + name;
}
public String CheckUserDB(String userToCheck){
String storedPassword = null;
String error_Message = null;
String SQL_Statement = null;
String error_Database;
Connection conn;
try {
conn = ds.getConnection();
try {
conn.setAutoCommit(false);
boolean committed = false;
try {
SQL_Statement = "SELECT Passwd from USERS WHERE Username = ?";
PreparedStatement passwordQuery = conn.prepareStatement(SQL_Statement);
passwordQuery.setString(1, userToCheck);
ResultSet result = passwordQuery.executeQuery();
if(result.next()){
storedPassword = result.getString("Passwd");
}
conn.commit();
committed = true;
} finally {
if (!committed) conn.rollback();
}
}
finally {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return storedPassword;
}
}
This is the error stack of the Glassfish server: http://pastebin.com/tvHmspjh
I can successfully compile the code but when I try to open JSF page I get error. Maybe I have mistaken the try-catch statements.
Best wishes
I am getting the error: java.sql.SQLException: No suitable driver
I have imported the .jar file that is available here http://dev.mysql.com/downloads/mirror.php?id=13598
I am using Eclipse.
I am connecting to the DB with this code:
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBCon {
private static final String host = "jdbc:mysql://localhost";
private static final String port = "3306";
private static final String db = "mydb";
// private static final String user = "root";
// private static final String pwd = "";
private static final String user = "myusername";
private static final String pwd = "mypwd";
public Connection getCon() {
Connection con = null;
try {
String url = host + ":" + port + "/" + db;
con = DriverManager.getConnection(url, user, pwd);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
I then query the DB with this code:
package dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.sql.Connection;
import model.ClassPojo;
public class ARCSDao {
public ArrayList<ClassPojo> viewClasses() throws SQLException{
ArrayList<ClassPojo> classList = new ArrayList<ClassPojo>();
DBCon db = new DBCon();
Connection con = db.getCon();
Statement stmt;
ResultSet rs;
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM classes");
while(rs.next()){
ClassPojo aClass = new ClassPojo();
rs.getString("class_name");
rs.getString("class_uri");
classList.add(aClass);
}
return classList;
}
}
Add
Class.forName("com.mysql.jdbc.Driver").newInstance();
before
con = DriverManager.getConnection(url, user, pwd);
if this doesn't work double check that the jdbc driver (jar file) is included in your classpath