//连接MySQL的方法
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnection {
private static String DB_DRIVER = "com.mysql.jdbc.Driver";
private static String DB_URL = "jdbc:mysql://localhost:3306/test";
private static String DB_NAME = "root";
private static String DB_PASSWORD = "MySQLde密码";
public static Connection getConn(){
try {
Class.forName(DB_DRIVER);
Connection conn = DriverManager.getConnection(DB_URL, DB_NAME, DB_PASSWORD);
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
public calss DBConnection{
//建立一个静态方法,返回一个数据库的连接
//这样就可以达到对数据库进行统一管理的效果
public static Connection getConnection(){
Connection con = null;
String driver = "com.microsoft.jdbc.sqlserver.SQLSerDriver";
String severURL = "jdbc:microsoft:sqlserver://localhost:1433;DataBaseName=数据库名";
String username = "数据库用户名";
String password = "数据库密码";
try{
Class.forName(driver);
con = DriverManager.getConnection(severURL, username, password);
}catch(Exception e){
e.printStackTace();
}
}
}
例如:一个实体类要持久化
public class EntityClass{
private Connection con;
//通过构造方法获取数据库的连接
public EntityClass{
con = DBConnection.getConnection();
}
public Connection getInfo(){
PreparedStatement st = con.preparedStatement();
String sql = "sql 语句";
ResultSet rs = st.executeQuery(sql);
.......
//关闭数据库的连接
con.close();
.......
}
}