4步
- 加载驱动,有驱动才有链接
- 获取链接,通过驱动创建链接,有链接才有代理。
- 通过链接创建代理
- 结果集用来主要来接受select语句的查询结果。
package databasetool;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class DBTool {
private static final String driverManger = "com.mysql.jdbc.Driver";
private static Connection conn;
private static Statement stmt;
private static ResultSet rs;
public static Connection getconn() {
conn = null;
String url = "jdbc:mysql://localhost:3306/shopdb";
String user = "root";
String password = "passwd";
try {
Class.forName(driverManger);
try {
conn = (Connection) DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}
public static int update(String sql) {
conn = getconn();
int line = 0;
try {
stmt = (Statement) conn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
line = stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return line;
}
public static ResultSet query(String sql) {
conn = getconn();
rs = null;
try {
stmt = (Statement) conn.createStatement();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public static void close() {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}