1.连接SqlServer
package org.test01.utils;
import java.sql.*;
public class DButil {
/*
* 各种数据库的连接
*/
//连接SqlServer
public static String driver = "com.microsoft.sqlserver.jdbc.SQLSeriverDriver";//连接驱动
public static String url = "jdbc://localhost:1433;databaseName=数据库名";//
public static String uid = "";//用户名
public static String upwd = "";//用户密码
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url,uid,upwd);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//这里放的是url,用户名,密码
return conn;//返回conn
}
//关闭资源
public static void close(ResultSet rs,Statement stmt,Connection conn) {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//测试连接是否正常
public static void main(String[] args) {
System.out.println(getConnection());
}
}
2.连接mysql也是一样的。
驱动换成String driver = "com.mysql.jdbc.Driver";
url为jdbc:mysql://:127.0.0.1;数据库名;
后面的用户和密码如上所示,都是你数据库的用户名和密码
后面还有几个数据库连接,没写上