Java连接MySQL数据库过程封装成类
package connect;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DataBaseConnect {
// private String dbName, user, pass;
private Connection connection = null;
private Statement statement = null;
private ResultSet result = null;
//设置数据库信息
// public void set(String dbName, String user, String pass) {
// this.dbName = dbName;
// this.user = user;
// this.pass = pass;
// }
//连接数据库
public boolean connect(String dbName, String user, String pass) {
String URL1 = "jdbc:mysql://localhost:3306/";
String URL2 = "?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
//加载驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
}
//建立连接
try {
this.connection = DriverManager.getConnection(URL1 + dbName + URL2, user, pass);
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
// public Statement getStatement() {
// try {
// return this.connection.createStatement();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
public ResultSet query(String sql) {
try {
this.statement=this.connection.createStatement();
return (this.statement.executeQuery(sql));
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
将Java连接数据所要用到的方法封装成DataBaseConnect类,调用其中的connect方法后就可以成功连接上数据库。
使用封装后的DataBaseConnect类连接数据库
package test;
import connect.DataBaseConnect;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ConnectTest {
public static void main(String[] args) {
DataBaseConnect dbc = new DataBaseConnect();
//调用connect方法连接数据库,connect("数据库名","用户名","密码")
boolean var = dbc.connect("websql","root","root");
ResultSet rs=null;
if (var) {
System.out.println("数据库连接成功");
//调用dbc对象中的query方法,将SQL语句作为字符串参数传递,可以返回结果集
rs = dbc.query("select * from goods");
try {
while (rs.next()) {
System.out.print(rs.getInt("id") + " ");
System.out.print(rs.getString("gname") + " ");
System.out.print(rs.getDouble("gprice") + " ");
System.out.println("");
}
} catch (SQLException e) {
e.printStackTrace();
}
} else {
System.out.println("数据库连接失败");
}
}
}