1.MySQL:
package com.text.tools;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/***
* 连接MySql数据库
*@author <a href="mailto:qihao@ssreader.cn">chenqihao</a>
*@version 2013-3-9
*/
public class JDBCConn {
public Connection getConnection() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/books";
String user = "root";
String password = "123";
Connection conn = null;
try {
Class.forName(driver);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(url, user, password);
if (!conn.isClosed())
System.out.println("Succeeded connecting to the Database!");
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static void main(String[] args) {
JDBCConn jdbc = new JDBCConn();
System.out.println(jdbc.getConnection());
}
}
2.SQLServer:
package com.text.tools;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 链接SQLServer数据库内
* @author <a href="mailto:qihao@ssreader.cn">chenqihao</a>
*@version 2013-9-13
*/
public class JDBCConnSqlServer {
public Connection getConnectionSql() {
String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
String dbURL = "jdbc:microsoft:sqlserver://localhost:1433;databasename=li"; // 1433是数据库的端口,"li"是你的数据库名称
String userName = "sa"; // sa是数据库的超级用户,最好不要换别的名字,权限问题
String password = "123456"; // sa的密码
Connection dbConn = null;
try {
Class.forName(driverName).newInstance();
dbConn = DriverManager.getConnection(dbURL, userName, password);
System.out.println("连接成功!");
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (dbConn != null)
dbConn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
public static void main(String[] args) {
JDBCConnSqlServer jdbc = new JDBCConnSqlServer();
System.out.println(jdbc.getConnectionSql());
}
}
3.Oracle:
package com.text.tools;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Oracle链接数据库类
* @author <a href="mailto:qihao@ssreader.cn">chenqihao</a>
*@version 2013-9-13
*/
public class JDBCConnOracle {
public static Connection getConnection() {
// 定义一个连接对象
Connection conn = null;
// 定义连接数据库的URL资源
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
// 定义连接数据库的用户名称与密码
String username = "scott";
String password = "tiger";
// 加载数据库连接驱动
String className = "oracle.jdbc.driver.OracleDriver";
try {
Class.forName(className);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
// 获取数据库的连接对象
try {
conn = DriverManager.getConnection(url, username, password);
System.out.println("数据库连接建立成功...");
}
catch (SQLException e) {
e.printStackTrace();
}
// 返回连接对象
return conn;
}
public static void main(String[] args) {
JDBCConnOracle jdbc = new JDBCConnOracle();
System.out.println(jdbc.getConnection());
}
}