简体   繁体   English

使用存储的数据库信息执行sql查询java

[英]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. 我是Java的新手,我有c#的经验,我也想尝试一下java,因为它是我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. 用c#完成一些项目后,我注意到我犯的一个重大错误是我没有将数据库连接详细信息存储在一个地方。 (I used to include the connection string everytime i executed a query) (我每次执行查询时都会包含连接字符串)
Im creating a simple login form for starters. 我为初学者创建了一个简单的登录表单。

sqlDB.java 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 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 sqlDB.java in Login.java, to execute a query like 我如何在Login.java中使用sqlDB.java中的数据库连接来执行查询

"'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 例如,您可以执行以下操作: 检查SQL登录凭据

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. 或者,您可以简单地对将始终包含某些内容的表执行SQL查询(例如Select * From Humans Where HumanID = 1; ),然后检查是否获得结果,但这有点草率和不良做法。

This is the Java code for the Initializing the MS SQL Connection 这是用于初始化MS SQL连接的Java代码
File Name: DatabaseCon.java 文件名:DatabaseCon.java

/**
 *
 * @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). 这是一个简单的Java表单,它使用SQL连接检查数据库中是否存在某些记录(简单登录表单)。

Login Button Click Event Triggers the following code 登录按钮单击事件触发以下代码

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. 该代码的主要目的是将SQL连接保存在另一个Java文件中,并在整个程序中使用该连接,因此您不必每次升级或更改SQL Server时都更改服务器设置。 Just modifying the SQL Connection file will do! 只需修改SQL Connection文件即可!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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