JDBC如何获取数据库连接?

2025-01-02 14:48:11
推荐回答(2个)
回答1:

关键代码:
public Connection connecting(){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
try{
connect=DriverManager.getConnection("jdbc:oracle:thin:SYSTEM@//localhost:1521/ORCL","SCOTT","tiger");//SYSTEM@//localhost:1521/ORCL为数据库链接地址,Scott用户名,tiger为密码//
}catch(SQLException e){
e.printStackTrace();
}
return connect;
}

回答2:

public class SQLLink {
private static String url="jdbc:sqlserver://localhost:1433;databaseName=MailBox";
private static String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static String username="sa";
private static String password="wsh";
private static Connection conn;

static{
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getconn(){
try {

conn=DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}

public static void closeconn(){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}