注意导包的问题,越是微小的错误越容易犯!!!
1、连接MySQL数据库
public class JDBCTool {
public static Connection getConn() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String url="jdbc:mysql://localhost:3306/temp?useUnicode=true&characterEncoding=utf-8";
try {
Connection conn = DriverManager.getConnection(url, "登录名", "密码");
return conn;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
2、连接Oracle 数据库
package com.wx.util;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBUtil {
/*方法一*/
public static Connection getConnection() throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","登录名","密码");
return connection;
}
public static Connection getConnection() throws Exception {
/*方法二*/
Context context=new InitialContext();
DataSource ds= (DataSource) context.lookup("jdbc:oracle:thin:@localhost:1521:orcl");
return ds.getConnection();
}
}
(以上为两种写法,看看需要哪种)
3、连接SQL server数据库:
package renao.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBUtil {
public static Connection getConnection() throws Exception {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection
("jdbc:sqlserver://ip地址:1433;DatabaseName=数据库名称", "登录名","密码");
return conn;
}
}
注释:
1433为端口号;
DatabaseName为数据库名称,若数据库名称有好多个,就看看SQL server默认的数据库名称是哪个,避免出错;
登录名和密码就不细说了,大家清楚。
附:
查看SQL server默认数据是哪个,点中所选择的数据库,右键属性,点击–查看连接属性–,看看数据库默认连接的那个数据库。
希望可以帮助到一些!