简体   繁体   中英

use stored database info to execute sql queries java

Im new to Java, i have experience in c# and i wanted to try out java aswell as it is the programming language used in my uni.
After completing some projects with c#, i noticed one of the big mistakes i made was that i didnt store database connection details at one place. (I used to include the connection string everytime i executed a query)
Im creating a simple login form for starters.

sqlDB.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class sqlDB{



    public Connection connect() {
    Connection con = null;
     String url = "jdbc:sqlserver//SERVER IP";
    String db = "DBNAME";
    String driver = "com.mysql.jdbc.Driver";
    String user = "USERNAME";
    String pass = "PASSWORD";
    try {
        Class.forName(driver);
        con = DriverManager.getConnection(url + db, user, pass);
        if (con == null) {
            System.out.println("Connection cannot be established");
        }
        return con;
    } catch (Exception e) {
        System.out.println(e);
    }
    return null;
}



}

Login.java

This is the Login button event

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        String username = usernameText.getText(); // username textbox value
        String password = passwordText.getText(); // password textbox value
    }    

How do i use the Database Connection in in Login.java, to execute a query like 中使用中的数据库连接来执行查询

"'Select user,pass from login where user='"+username+"' and pass='"+password+"' 

Then check the number or rows to login..

There are possibilities to check your credentials with your database, it depends what Database you use. For example, you could do something like this: Check credentials of SQL Login

Scince you did not mention what Database you use, go ahead and look for a solution that fits your system.

Other options are to store your password locally (encrypted) and compare it offline.

Or you could simply do an SQL query to an table that will always contain something (something like Select * From Humans Where HumanID = 1; ) and check if you get a result but thats kind of sloppy and bad practice.



/**
 *
 * @author Charindu Edirisuriya
 */
package dash.control;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class DatabaseCon{



  public Connection connect() {

    Connection con = null;
      String url = "jdbc:sqlserver://HOST;DatabaseName=DATABASENAME";
      String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; 
      String user = "USERNAME";
      String pass = "PASSWORD";
    try {
        Class.forName(driver);
        con = DriverManager.getConnection(url, user, pass);
        if (con == null) {
            System.out.println("Connection cannot be established");
        }
        return con;
    } catch (Exception e) {
        System.out.println(e);
    }
    return null;
}



}

This is a simple Java Form which uses the SQL connection to check if some records exist in the Database or not (Simple Login Form).

Connection connection;
PreparedStatement ps;

String username = usernameText.getText(); // Usename Textbox
String password = String.valueOf(passwordText.getPassword()); //Password Textbox


try{ 
  DatabaseCon db = new DatabaseCon();
  connection = db.connect();
  ps = connection.prepareStatement("SELECT Username, Password FROM Login WHERE Username = ? AND Password = ?");
     ps.setString(1, username);
     ps.setString(2, password);
  ResultSet result = ps.executeQuery();
    if(result.next()){
        System.out.println("Login Successesfully");
        new Main_Form().setVisible(true); //Loads new Form
        this.setVisible(false);



        }
        else{
            System.out.println("Invalide Username Or Password");

        }
   }
   catch(Exception e) {
    System.out.println(e);
    JOptionPane.showMessageDialog(null, "Check your Internet Connection!","Iane error",JOptionPane.ERROR_MESSAGE);
}

The Main objective of this code was to save the SQL Connection in a different java file and using that connection throughout the program, so you wont have to change the server settings every time to upgrade or change SQL Servers. Just modifying the SQL Connection file will do!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM