跨平台
将静态方法中写死的字符串改成从配置文件中获取。用户可以根据需要更改配置文件,而不用知道程序源码,使用编译后的class文件 和 更改后的配置文件即可正常运行。
代码
test.java
package jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class test {
public static void main(String[] args) throws SQLException {
// TODO 自动生成的方法存根
Scanner scanner = new Scanner(System.in);
System.out.println("请输入账号");
String user = scanner.nextLine();
System.out.println("请输入密码");
String password = scanner.nextLine();
scanner.close();
String sql = "select * from register where user=? and password=?";
Connection connection = dbutils.GetConnection();
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, user);
statement.setString(2, password);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
String str1 = resultSet.getString(1);
String str2 = resultSet.getString(2);
String str3 = resultSet.getString(3);
System.out.println(str1+";"+str2+";"+str3);
}
dbutils.CloseAll(connection, statement, resultSet);
}
}
dbutil.java
package jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//重用性方案
import java.util.Properties;
public class dbutils {
private static final Properties PROPERTIES=new Properties();
static {//类加载,执行一次
InputStream is = dbutils.class.getResourceAsStream("/db.properties");
try {
PROPERTIES.load(is);
Class.forName(PROPERTIES.getProperty("driver"));
} catch (ClassNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
catch (IOException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
}
public static Connection GetConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(
PROPERTIES.getProperty("url"),
PROPERTIES.getProperty("user"),
PROPERTIES.getProperty("password")
);
}
catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return connection;
}
public static void CloseAll(Connection connection, Statement statement,ResultSet resultSet) {
try {
if (resultSet!=null) {
resultSet.close();
}
if (statement!=null) {
statement.close();
}
if (connection!=null) {
connection.close();
}
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
配置文件db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/login
user=root
password=981002