如果是测试写个类就行,我自己写了一个你参考下
[Asm] 纯文本查看 复制代码 import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class JDBCTestTool {
static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB";
static String USER = "root";
static String PASS = "123456";
public JDBCTestTool(){
//这里是读取配置文件db.properties,如果没有可以注释掉
/**
Properties prop = new Properties();
try {
String path = JDBCTestTool.class.getResource("/").toString();
path = path.replaceAll("file:", "")+"db.properties";
prop.load(new FileInputStream(path));
System.out.println(prop.getProperty("driver"));
JDBC_DRIVER = prop.getProperty("driver");
DB_URL = prop.getProperty("url");
USER = prop.getProperty("username");
PASS = prop.getProperty("password");
System.out.println(JDBC_DRIVER+" , url: "+DB_URL+", user: "+USER+", pwd: "+PASS);
} catch (Exception e) {
e.printStackTrace();
}
**/
}
public Connection getConnection(){
Connection conn = null;
try{
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
DriverManager.setLoginTimeout(15);
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行查询
System.out.println(" 连接成功: "+conn.toString());
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
public static void main(String[] args) {
JDBCTestTool jdbcTestTool = new JDBCTestTool();
Connection conn = null;
try{
conn = jdbcTestTool.getConnection();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
} |