public class OpSQL{
// JDBC 驱动名及数据库 URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB?useUnicode=true&characterEncoding=utf-8&useSSL=false";
// 数据库的用户名与密码,需要根据自己的设置
String USER = "testuser";
String PASS = "1234";
//操作变量
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
public void Connect() {
try{
// 注册 JDBC 驱动
Class.forName("com.mysql.jdbc.Driver");
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行查询
System.out.println(" 实例化Statement对象...");
stmt = conn.createStatement();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
}
System.out.println("Goodbye!");
}
public void Close(){
try {
if(rs!=null) rs.close();
}catch (SQLException se3) {se3.printStackTrace();}
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){se2.printStackTrace();}
try{
if(conn!=null) conn.close();
}catch(SQLException se){se.printStackTrace();}
}
public void SelectCommand(String command) {//查询
try {
rs = stmt.executeQuery(command);
}catch (SQLException e){e.printStackTrace();}
}
public void Test()
{
try {
while (rs.next()) {
// 通过字段检索
int id = rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 站点名称: " + name);
System.out.print(", 站点 URL: " + url);
System.out.print("\n");
}
}catch (SQLException e){e.printStackTrace();}
}
public void SetUSER(String str)
{
USER = str;
}
}
改进连接MySQL为Class;原文:http://www.runoob.com/java/java-mysql-connect.html