先写一个封装的类,每次访问就可以直接实例化一个对象,然后连接数据库。
import java.sql.*;
public class DBCon {
// JDBC 驱动名及数据库 URL
private final String JDBC_DRIVER = "com.mysql.jdbc.Driver";//驱动名称
private final String DB_URL = "jdbc:mysql://120.78.175.234:3306/";//数据库地址
private final String DB_NAME = "signdb";//数据库名称
// 数据库的用户名与密码
private final String USER = "username";
private final String PASSWORD = "password";
private Connection con = null;
private Statement statement = null;
public DBCon() {
//加载驱动
try {
Class.forName(JDBC_DRIVER);
} catch (ClassNotFoundException classnotfoundexception) {
System.out.println("Can not find driver!");
classnotfoundexception.printStackTrace();
}
//连接数据库
try {
con = DriverManager.getConnection(DB_URL + DB_NAME,USER,PASSWORD);
statement = con.createStatement();
} catch (SQLException sqlexception) {
System.out.println("Connect fail!");
sqlexception.printStackTrace();
}
}
//关闭数据库
public void close() {
try {
statement.close();
con.close();
} catch (SQLException sqlexception) {
sqlexception.printStackTrace();
}
}
//执行查询sql
public ResultSet executeQuery(String querySql) {
ResultSet resultset = null;
try {
resultset = statement.executeQuery(querySql);
} catch (SQLException sqlexception) {
sqlexception.printStackTrace();
}
return resultset;
}
//执行增删改等sql
public void executeUpdate(String sql) {
try {
System.out.println("DBCon executeUpdate:" + sql);
statement.execute(sql);
} catch (SQLException sqlexception) {
sqlexception.printStackTrace();
}
}
}
现在测试一下这个类是否可用。
import java.sql.ResultSet;
import java.sql.SQLException;
public class testDB
{
public static void main(String args[]) throws SQLException
{
DBCon testdb = new DBCon();
String name = "faive";
String sql = "SELECT * FROM user WHERE username = '"+name+"'";
ResultSet rs = testdb.executeQuery(sql);
while (rs.next()){
System.out.println("ID: " + rs.getInt(1));
System.out.println("姓名: " + rs.getString("username"));
System.out.println("密码: " + rs.getString("password"));
}
}
}