1 import java.sql.Connection;
創(chuàng)新互聯(lián)公司是一家專注于成都網(wǎng)站建設(shè)、成都做網(wǎng)站與策劃設(shè)計,江都網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)10年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:江都等地區(qū)。江都做網(wǎng)站價格咨詢:18982081108
2 import java.sql.DriverManager;
3 import java.sql.ResultSet;
4 import java.sql.SQLException;
5 import java.sql.Statement;
6
7 public class CreateDataSource {
8
9 /**
10 * @param args
11 */
12 public static void main(String[] args) {
13 // TODO Auto-generated method stub
14 String database = "test2";
15 new CreateDataSource().getConn(database);
16 }
17
18 String mysqlDriver = "com.mysql.jdbc.Driver";
19 String url = "jdbc:mysql://localhost:3306/test1";
20 String newUrl = "jdbc:mysql://localhost:3306/";
21 String username = "root";
22 String password = "root";
23 Connection conn = null;
24 Connection newConn = null;
25
26 public Connection getConn(String database) {
27
28 try {
29 Class.forName(mysqlDriver);
30 } catch (ClassNotFoundException e) {
31 // TODO Auto-generated catch block
32 e.printStackTrace();
33 }
34 try {
35 String tableSql = "create table t_user (username varchar(50) not null primary key,"
36 + "password varchar(20) not null ); ";
37 String databaseSql = "create database " + database;
38
39 conn = DriverManager.getConnection(url, username, password);
40 Statement smt = conn.createStatement();
41 if (conn != null) {
42 System.out.println("數(shù)據(jù)庫連接成功!");
43
44 smt.executeUpdate(databaseSql);
45
46 newConn = DriverManager.getConnection(newUrl + database,
47 username, password);
48 if (newConn != null) {
49 System.out.println("已經(jīng)連接到新創(chuàng)建的數(shù)據(jù)庫:" + database);
50
51 Statement newSmt = newConn.createStatement();
52 int i = newSmt.executeUpdate(tableSql);//DDL語句返回值為0;
53 if (i == 0) {
54 System.out.println(tableSql + "表已經(jīng)創(chuàng)建成功!");
55 }
56 }
57 }
58
59 } catch (SQLException e1) {
60 // TODO Auto-generated catch block
61 e1.printStackTrace();
62 }
63 return conn;
64 }
65 }
createStatement 這個不是報錯,只是這句可能會拋出異常,這種情況在java中是必須使用 try catch 捕捉的。 你只要把代碼塊用 try catch 包起來就可以了。
用這個類吧.好的話,給我加加分.
import java.sql.*;
/**
* @功能: 一個JDBC的本地化API連接類,封裝了數(shù)據(jù)操作方法,只用傳一個SQL語句即可
* @作者: 李開歡
* @日期: 2007/
*/
public class ConnectionDemo {
/*
* 這里可以將常量全部放入另一個類中,以方便修改
*/
private static Connection conn;
private static Statement ps;
private static ResultSet rs;
private static final String DRIVER = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
private static final String URL = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb";
private static final String USER ="sa";
private static final String PASS = "sa";
public ConnectionDemo() {
// TODO Auto-generated constructor stub
ConnectionDemo.getConnection();
}
public static Connection getConnection(){
System.out.println("連接中...");
try {
Class.forName(ConnectionDemo.DRIVER);
conn = DriverManager.getConnection(ConnectionDemo.URL, ConnectionDemo.USER, ConnectionDemo.PASS);
System.out.println("成功連接");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static Statement getStatement(String sql){
System.out.println("執(zhí)行SQL語句中...");
try {
ps = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
if(sql.substring(0, 6).equals("select")){
rs = ps.executeQuery(sql);
System.out.println("執(zhí)行完查詢操作,結(jié)果已返回ResultSet集合");
}else if(sql.substring(0, 6).equals("delete")){
ps.executeUpdate(sql);
System.out.println("已執(zhí)行完畢刪除操作");
}else if(sql.substring(0, 6).equals("insert")){
ps.executeUpdate(sql);
System.out.println("已執(zhí)行完畢增加操作");
}else{
ps.executeUpdate(sql);
System.out.println("已執(zhí)行完畢更新操作");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ps;
}
public static ResultSet getResultSet(){
System.out.println("查詢結(jié)果為:");
return rs;
}
public static void closeConnection(){
System.out.println("關(guān)閉連接中...");
try {
if (rs != null) {
rs.close();
System.out.println("已關(guān)閉ResultSet");
}
if (ps != null) {
ps.close();
System.out.println("已關(guān)閉Statement");
}
if (conn != null) {
conn.close();
System.out.println("已關(guān)閉Connection");
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ConnectionDemo.getConnection();
String sql = "delete from type where id = 1";
ConnectionDemo.getStatement(sql);
String sql2 = "insert into type values(1,'教學(xué)設(shè)備')";
ConnectionDemo.getStatement(sql2);
String sql1 = "select * from type";
ConnectionDemo.getStatement(sql1);
ResultSet rs = ConnectionDemo.getResultSet();
System.out.println("編號 "+"類 型");
try {
while(rs.next()){
System.out.print(" "+rs.getInt(1)+" ");
System.out.println(rs.getString(2));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ConnectionDemo.closeConnection();
}
}
以上的代碼都不如哥的 且看哥是怎么寫條理清晰的代碼的?。?!
package dbconnection //java 中不存在沒有包的類(講解詳細(xì)因為項目需要)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;//引入sql數(shù)據(jù)庫包
public class DBConnection{
private Connection conn=null;
private Statement stmt=null;
private Result rs=null;
private String jdbc="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private String driverManager="jdbc:sqlserver://localhost:1433;databasename=HcitPos";
private String user="admin";
private int password="admin";
public DBConnection{
try{
Class.forName("jdbc");
conn.getConnection("driverManager");
}
catch(Exception e){}
}
public selectMethod(String sql){
stmt=conn.createStatement();
rs=stmt.extcuteQuery("sql");
while(rs.next()){
String title=rs.getString("title");//利用javaBean獲得數(shù)據(jù)庫中的屬性
String name=rs.getString("name");
.......
System.out.println("title");
System.out.println("name");
......
//當(dāng)然數(shù)據(jù)庫的操作有很多 這里簡單介紹下功能的實現(xiàn)
}
}
public void closeDB(){
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(conn != null) conn.close();
}
}
1. 加載一個對應(yīng)數(shù)據(jù)庫的JDBC驅(qū)動
在建立到一個數(shù)據(jù)庫的連接之前,必須先加載這個數(shù)據(jù)庫的JDBC驅(qū)動程序,加載之后此driver會自動注冊到JDBC驅(qū)動列表中。加載一個JDBC驅(qū)動有兩種方法。
a) 在命令行方式下指定驅(qū)動器或者用冒號分割驅(qū)動器列表:
具體命令如下:
C:\java –Djdbc.drivers = com.company1.Driver:com.company2.Driver youProject
b)第二種方法,在程序中調(diào)用Class.forName()方法。推薦使用。。。。
try
{
String driverName = “com.imaginary.sql.msql.MsqlDriver”;
Class.forName(driverName).newInstance();
}
Catch(ClassNotFoundException e1)
{
//catch could not find database driver exception.
}
2.連接到數(shù)據(jù)庫。
根據(jù)您后臺待連接的數(shù)據(jù)庫不同,而有小小的差別。
a) 連接到Oracle數(shù)據(jù)庫。
Connection connection = null ;
try
{
//load the jdbc driver ;
String driverName = “oracle.jdbc.driver.OracleDriver”;
Class.forName(driverName).newInstance();
//create a connection to the database;
String serverName = “127.0.0.1”;
String serverPort = “1521”;
String serverID = “datebase1”
String userName = “hello”;
String userPsw = “world”;
String url = “jdbc:oracle.thin:@” + serverName + “:” + serverPort + “:” + serverID ;
Connection = DriverManager.getConnection(url , userName , userPsw);
}
catch(ClassNotFoundException e1)
{
//catch could not find database driver exception.
}
catch(SQLException e2)
{
//catch could not connect to the database exception.
}
b) 連接到一個SQL Server數(shù)據(jù)庫。
Connection connection = null ;
try
{
//load the jdbc driver ;
String driverName = “com.microsoft.jdbc.sqlserver.SQLServerDriver”;
Class.forName(driverName).newInstance();
//create a connection to the database;
String serverName = “127.0.0.1”;
String serverPort = “1433”;
String serverID = serverName + serverPort ;
String userName = “hello”;
String userPsw = “world”;
String url = “jdbc:JSQLConnect ://” + serverID ;
Connection = DriverManager.getConnection(url , userName , userPsw);
}
catch(ClassNotFoundException e1)
{
//catch could not find database driver exception.
}
catch(SQLException e2)
{
//catch could not connect to the database exception.
}
c) 連接到一個MySQL數(shù)據(jù)庫上。。。。
Connection connection = null ;
try
{
//load the jdbc driver ;
String driverName = “org.gjt.mm.mysql.Driver”;
Class.forName(driverName).newInstance();
//create a connection to the database;
String serverName = “127.0.0.1”;
String serverID = “database”;
String userName = “hello”;
String userPsw = “world”;
String url = “jdbc:mysql ://” + serverName + “/” + serverID ;
Connection = DriverManager.getConnection(url , userName , userPsw);
}
catch(ClassNotFoundException e1)
{
//catch could not find database driver exception.
}
catch(SQLException e2)
{
//catch could not connect to the database exception.
}
綜合上面的三種數(shù)據(jù)庫連接方式 , 其實大同小異。由于訪問不同的數(shù)據(jù)庫和所使用的數(shù)據(jù)庫驅(qū)動程序不同,所以導(dǎo)致代碼表面上有小小不同,但透過表面看來,內(nèi)部都是
1. 加載一個特定的數(shù)據(jù)庫JDBC驅(qū)動。
2. 連接到一個數(shù)據(jù)庫。
3. 之后,就可以對一個特定的數(shù)據(jù)庫進(jìn)行特定的操作了。
附上各種數(shù)據(jù)庫的JDBC驅(qū)動起可用信息網(wǎng)址:
對于Oracle數(shù)據(jù)庫,請參考:
對于MySQL數(shù)據(jù)庫,請參考:
對于SQL Server數(shù)據(jù)庫,有很多的驅(qū)動可選,比較常用的: