程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> java使用jdbc連接sqlserver、mysql、orcale

java使用jdbc連接sqlserver、mysql、orcale

編輯:關於JAVA

Java連接sqlserver

import Java.sql.*;public class TestDB {
public static void main(String[] args) {
String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
String dbURL = "jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=pubs";
String userName = "sa";
String userPwd = "";
Connection dbConntry {
Class.forName(driverName);
dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
System.out.println("Connection Successful!");
}
Catch (Exception e) {
e.printStackTrace();
}
}
}

Java連接MySQL

import Java.sql.*;public class SampleIntro
{
  public static void main(String[] args)
  {
    try
    {
      Connection conn;
      Statement stmt;
      ResultSet res;
      //加載Connector/J驅動
      //這一句也可寫為:Class.forName("com.MySQL.jdbc.Driver");
      Class.forName("com.MySQL.jdbc.Driver").newInstance();
      //建立到MySQL的連接
      conn = DriverManager.getConnection("jdbc:MySQL://localhost:3306/test",
                                         "root", "guapo");
      //執行SQL語句
      stmt = conn.createStatement();
      res = stmt.executeQuery("select * from pet");
      //處理結果集
      while (res.next())
      {
        String name = res.getString("name");
        System.out.println(name);
      }
      res.close();    }
    catch (Exception ex)
    {
      System.out.println("Error : " + ex.toString());
    }
  }
}

Java連接Oracle

(1) 使用jdbc-odbc橋接:

// 使用本地的jdbc連接串,查詢Oracle數據庫表
import Java.sql.*;public class lookup {
public static void main(String[] args)
throws SQLException, ClassNotFoundException {
//定義了數據庫連接串
String dbUrl = "jdbc:odbc:dbjdbc";
//數據庫的用戶名
String user = "manager";
//數據庫的用戶口令
String passWord = "ora912";
// 加載jdbc-odbc bridge驅動程序
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// 與url指定的數據源建立連接
Connection c = DriverManager.getConnection(dbUrl, user, passWord);
//采用Statement進行查詢
Statement s = c.createStatement();
ResultSet r = s.executeQuery("SELECT empno,name from emp");
while(r.next()) {
// 打印字段信息
System.out.println(r.getString("empno") + ",
" + r.getString("name ") );
}
// 關閉Statement,其上的ResultSet也將關閉
s.close();
}
} (2)jdbc import Java.sql.*;
public class TestOracleDriver {
public static void main(String[] args)
throws SQLException, ClassNotFoundException {
String dbUrl = "jdbc:Oracle:thin:@127.0.0.1:1521:yy";
String user = "admin";
String passWord = "123";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection c = DriverManager.getConnection(dbUrl, user, passWord);
Statement s = c.createStatement();
ResultSet r = s.executeQuery("SELECT * from dloginmsg");
while(r.next()) {
System.out.println(r.getString(2) + "," + r.getString(1) );
}
s.close();
}
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved