private static String url="jdbc:mysql://localhost:3306/mvc";
private static String user="root";
private static String password="root";
private static Statement stmt = null;
private static Connection conn = null;
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn=(Connection) DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void closeConnection(Statement stmt,Connection conn){
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
读取db.properties进行数据库连接
//db.properties
url=jdbc:mysql://localhost:3306/oa
user=root
password=root
public static Connection getConnection(){
Connection conn=null;
Properties props=new Properties();
InputStream in = DbUtil.class.getResourceAsStream("/db.properties");
try {
props.load(in);
String url=props.getProperty("url");
String user=props.getProperty("user");
String password=props.getProperty("password");
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void close(Connection conn,Statement stmt){
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection conn,Statement stmt,ResultSet rs){
close(conn,stmt);
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
jdbc连接各种数据库参数
JDBC的URL=协议名+子协议名+数据源名。
a 协议名总是“jdbc”。
b 子协议名由JDBC驱动程序的编写者决定。
c 数据源名也可能包含用户与口令等信息;这些信息也可单独提供。
几种常见的数据库连接
-------------------------------oracle------------------
驱动:oracle.jdbc.driver.OracleDriver
URL:jdbc:oracle:thin:@machine_name:port:dbname
注:machine_name:数据库所在的机器的名称;
port:端口号,默认是1521
-------------------------------mysql-------------------
驱动:com.mysql.jdbc.Driver
URL:jdbc:mysql://machine_name:port/dbname
注:machine_name:数据库所在的机器的名称;
port:端口号,默认3306
---------------------------SQL Server------------------
驱动:com.microsoft.jdbc.sqlserver.SQLServerDriver
URL:jdbc:microsoft:sqlserver://<machine_name><:port>
注:machine_name:数据库所在的机器的名称;
port:端口号,默认是1433
--------------------------DB2--------------------------
驱动:com.ibm.db2.jdbc.app.DB2Driver
URL:jdbc:db2://<machine_name><:port>/dbname
注:machine_name:数据库所在的机器的名称;
port:端口号,默认是5000
-------------------------------------------------------