java语言Oracle、SQLServer、MySQL数据库的连接方法

时间:2021-08-11 04:23:40

概要:下面分了三种连接的方式:其实除了URL的书写格式不同,java进行数据库连接的代码是完全一样的;当然URL书写的不同导致所需要的驱动jar也不相同;

USERNAME也因数据库的不同而不同,Oracle、SQLServer、MySQL数据库默认分别为scott、sa、root,PASSWORD密码自设;同时建议使用2 和 3 中的那种规范的书写方式,具有通用性质。因此,对于对数据库比较了解的,有过开发经验的,可以直接跳过1 和 2或者仅仅看一看1 2的URL即可。

同时,建议大家把URL、USERNAME和PASSWORD这些final static 变量写在类似配置文件的(例如,以properties结尾的文件中,或者XML文件中),这样在数据库迁移 、工程部署以及代码合并时非常方便,这也符合开发的需要——把逻辑代码和用例代码分开,请看 4

1  java连接Oracle数据库(Oracle数据库的安装网上有教程,本人装的是32位系统)


注意本文所用的方法是通用的方法建立连接的jdbc的thin方式:
此种方法不需要安装Oracle的客户端,也不需要配置odbc,故此种方法用得比较普遍。 此方法在使用时需要将oracle的jar包加到classpath变量中,此包可以在oralce客户端程序的$ORACLE_HOME/jdbc/lib/classes12.jar找到(或者***\product\11.2.0\dbhome_1\jdbc\lib下的ojdbc6.jar buildpath到工程里面)。
如下:是自己建立的测试用例,测试通过

package tju.cs.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public classDBConn {

private static String URL = "jdbc:oracle:thin:@127.0.0.1:1521:sample";// 最后一项是自己所建立的数据库名称(sid)
private static String USERNAME = "scott";
private static String PASSWORD = "root";
public static Connection getCon(){
Connectionconn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn= DriverManager.getConnection(URL,USERNAME,PASSWORD);
}catch(Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(new DBConn().getCon());
//采用Statement进行查询
//String sql = "select * from student where sname= '张三'"; // 这样可以的哦,下面是更一般的形式:
Stringname = "张三";
Stringsql = "select * from student where sname ='"+name+"' ";
Connectionconn = getCon();
Statementstatement = null;
ResultSetrs = null;

try {
statement= conn.createStatement();
rs= statement.executeQuery(sql);
}catch(SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
while(rs.next()) {
// 打印字段信息
System.out.println(rs.getString("sname")+ ","+ rs.getString("sex") );
}
}catch(SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DBConn.close(conn,statement, rs);
}
public static void close(Connectioncon,Statement sm,ResultSet rs){
try {
if(con!=null){
con.close();
}
if(sm!=null){
sm.close();
}
if(rs != null){
rs.close();
System.out.println("手动执行DBConn类的static方法……");
}
}catch(SQLException e) {
e.printStackTrace();
}
}
}




2  java连接SQLServer数据库(SQLServer数据库的安装网上有教程,本人装的是32位系统)


package com.demo.javabean;// 工程所需要的驱动jar包是:mssqlserver.jar   msutil.jar  msbase.jar

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBAccess {

public static String drv ="com.microsoft.jdbc.sqlserver.SQLServerDriver";
public static String url ="jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=demoaa";
public static String usr ="sa";
public static String pwd ="root";
private Connection conn = null;
private Statement stm = null;
private ResultSet rs = null;

public boolean createConn() {
boolean b = false;
try {
Class.forName(drv);
conn=DriverManager.getConnection(url,usr,pwd);
b=true;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return b;
}

public boolean update(String sql) {
boolean b = false;
try {
stm = conn.createStatement();
stm.execute(sql);
b = true;
} catch (Exception e) {
System.out.println(e.toString());
}
return b;
}

public void query(String sql) {
try {
stm = conn.createStatement();
rs = stm.executeQuery(sql);
} catch (Exception e) {
e.printStackTrace();
}
}

public boolean next() {
boolean b = false;
try {
if(rs.next())b = true;
} catch (Exception e) {
}
return b;
}

public String getValue(String field) {
String value = "";
try {
if(rs!=null) value = rs.getString(field);
} catch (Exception e) {
e.printStackTrace();
}
if (value == null) value = "";
return value;
}

public void closeConn() {
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
}
}

public void closeStm() {
try {
if (stm != null)
stm.close();
} catch (SQLException e) {
}
}

public void closeRs() {try {if (rs != null)rs.close();} catch (SQLException e) {}}public Connection getConn() {return conn;}public void setConn(Connection conn) {this.conn = conn;}public ResultSet getRs() {return rs;}public void setRs(ResultSet rs) {this.rs = rs;}public Statement getStm() {return stm;}public void setStm(Statement stm) {this.stm = stm;}}
// 建议书写为这种格式,这是一个通用的公共类util

 

3  java连接MySQL数据库(MySQL数据库的安装网上有教程,本人装的是32位系统)

//需要的驱动包:mysql-connector-java-5.0.8-bin.jar

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBAccess {

//public static String drv ="com.microsoft.jdbc.sqlserver.SQLServerDriver";
public static String drv ="com.mysql.jdbc.Driver";//com.mysql.jdbc.Driver
//public static String url ="jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=demoaa";
public static String url ="jdbc:mysql://localhost:3306/TechSearch";
//public static String usr ="sa";
public static String usr ="root";
public static String pwd ="root";
private Connection conn = null;
private Statement stm = null;
private ResultSet rs = null;

public boolean createConn() {
boolean b = false;
try {
Class.forName(drv);
conn=DriverManager.getConnection(url,usr,pwd);
b=true;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return b;
}

public boolean update(String sql) {
boolean b = false;
try {
stm = conn.createStatement();
stm.execute(sql);
b = true;
} catch (Exception e) {
System.out.println(e.toString());
}
return b;
}

public void query(String sql) {
try {
stm = conn.createStatement();
rs = stm.executeQuery(sql);
} catch (Exception e) {
e.printStackTrace();
}
}

public boolean next() {
boolean b = false;
try {
if(rs.next())b = true;
} catch (Exception e) {
}
return b;
}

public String getValue(String field) {
String value = "";
try {
if(rs!=null) value = rs.getString(field);
} catch (Exception e) {
e.printStackTrace();
}
if (value == null) value = "";
return value;
}

public void closeConn() {
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
}
}

public void closeStm() {
try {
if (stm != null)
stm.close();
} catch (SQLException e) {
}
}

public void closeRs() {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
}
}

public Connection getConn() {
return conn;
}

public void setConn(Connection conn) {
this.conn = conn;
}

public ResultSet getRs() {
return rs;
}

public void setRs(ResultSet rs) {
this.rs = rs;
}

public Statement getStm() {
return stm;
}

public void setStm(Statement stm) {
this.stm = stm;
}
}

4  以java连接mysql为例,列举properties

    (1)DBConfig.properties: 这里可以写下所有的公共配置信息

DRIVER=com.mysql.jdbc.Driver
URL=jdbc\:mysql\://127.0.0.1\:3306/qq?useUnicode\=true&characterEncoding\=UTF-8
USERNAME=root
PASSWORD=root

#DRIVERNAME=oracle.jdbc.driver.OracleDriver
#URL=jdbc:oracle:thin:@127.0.0.1:1521:orcl
#USERNAME=scott
#PASSWORD=tiger
(2)  DBConfig.java  主要通过java.util.Properties的实例pro,load(filepath),进行加载配置信息,再通过pro.getProperty(key)返回key值所对应的value值,其实Properties相当于Hash的有键值对(key - value )

package com.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.swing.JOptionPane;

public class DBConfig {
//private String filepath="javabeantest\\src\\util\\JDBCconfig.properties";//error
//private String filepath="src\\util\\JDBCconfig.properties";//error
//private String filepath="javabeantest/src/util/JDBCconfig.properties";//error
//private String filepath="util\\JDBCconfig.properties";//error����ֻ�ʺϱ���·�������ܷŵ�tomcat�����Ŷ��
private String filepath = "/com/util/JDBCconfig.properties";//right tomcat and linux only right in this way..
//private String filepath = "\\com\\util\\JDBCconfig.properties";//error
//private String filepath = "//com//util//JDBCconfig.properties";//right tomcat
private Properties pro=new Properties();
private static DBConfig config=null;
public static DBConfig getIntance(){
if(config==null){
config=new DBConfig();
}
return config;
}
private DBConfig(){
try {
System.out.println(filepath);
//pro.load(new FileInputStream(filepath));

pro.load(getClass().getResourceAsStream(filepath));
} catch (Exception e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, "���ļ��Ҳ���");
}
}
public String getValue(String key){
return pro.getProperty(key);
}

}

(  3) DBUtil.java 此类通过DBConfig.java类里面的函数 返回Connection的实例,类里面全部是static 方法,直接可以用类名调用(这里有中文乱码,懒得改了)

package com.util;


import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;


import javax.swing.JOptionPane;


public class JDBCUtil {
static{
try {
Class.forName(DBConfig.getIntance().getValue("DRIVER"));
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, "����Ҳ���");
}

}

public static Connection getConnection(){
Connection conn = null;
try {

String url = DBConfig.getIntance().getValue("URL");
String user = DBConfig.getIntance().getValue("USERNAME");
String pwd = DBConfig.getIntance().getValue("PASSWORD");
System.out.println(url+user+pwd+"&&&&&");
conn = DriverManager.getConnection(url, user, pwd);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"��ȡ**����ʧ��");

}
return conn;
}

public static void close(ResultSet set,Statement stmt,Connection conn){
try {
if(set!=null){
set.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try{
if(stmt!=null){
stmt.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try{
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}