1 import java.sql.Connection;
创新互联公司是一家专注于成都网站建设、成都做网站与策划设计,江都网站建设哪家好?创新互联公司做网站,专注于网站建设10年,网设计领域的专业建站公司;建站业务涵盖:江都等地区。江都做网站价格咨询: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("数据库连接成功!");
43
44 smt.executeUpdate(databaseSql);
45
46 newConn = DriverManager.getConnection(newUrl + database,
47 username, password);
48 if (newConn != null) {
49 System.out.println("已经连接到新创建的数据库:" + database);
50
51 Statement newSmt = newConn.createStatement();
52 int i = newSmt.executeUpdate(tableSql);//DDL语句返回值为0;
53 if (i == 0) {
54 System.out.println(tableSql + "表已经创建成功!");
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连接类,封装了数据操作方法,只用传一个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("执行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("执行完查询操作,结果已返回ResultSet集合");
}else if(sql.substring(0, 6).equals("delete")){
ps.executeUpdate(sql);
System.out.println("已执行完毕删除操作");
}else if(sql.substring(0, 6).equals("insert")){
ps.executeUpdate(sql);
System.out.println("已执行完毕增加操作");
}else{
ps.executeUpdate(sql);
System.out.println("已执行完毕更新操作");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ps;
}
public static ResultSet getResultSet(){
System.out.println("查询结果为:");
return rs;
}
public static void closeConnection(){
System.out.println("关闭连接中...");
try {
if (rs != null) {
rs.close();
System.out.println("已关闭ResultSet");
}
if (ps != null) {
ps.close();
System.out.println("已关闭Statement");
}
if (conn != null) {
conn.close();
System.out.println("已关闭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,'教学设备')";
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 中不存在没有包的类(讲解详细因为项目需要)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;//引入sql数据库包
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获得数据库中的属性
String name=rs.getString("name");
.......
System.out.println("title");
System.out.println("name");
......
//当然数据库的操作有很多 这里简单介绍下功能的实现
}
}
public void closeDB(){
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(conn != null) conn.close();
}
}
1. 加载一个对应数据库的JDBC驱动
在建立到一个数据库的连接之前,必须先加载这个数据库的JDBC驱动程序,加载之后此driver会自动注册到JDBC驱动列表中。加载一个JDBC驱动有两种方法。
a) 在命令行方式下指定驱动器或者用冒号分割驱动器列表:
具体命令如下:
C:\java –Djdbc.drivers = com.company1.Driver:com.company2.Driver youProject
b)第二种方法,在程序中调用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.连接到数据库。
根据您后台待连接的数据库不同,而有小小的差别。
a) 连接到Oracle数据库。
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数据库。
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数据库上。。。。
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.
}
综合上面的三种数据库连接方式 , 其实大同小异。由于访问不同的数据库和所使用的数据库驱动程序不同,所以导致代码表面上有小小不同,但透过表面看来,内部都是
1. 加载一个特定的数据库JDBC驱动。
2. 连接到一个数据库。
3. 之后,就可以对一个特定的数据库进行特定的操作了。
附上各种数据库的JDBC驱动起可用信息网址:
对于Oracle数据库,请参考:
对于MySQL数据库,请参考:
对于SQL Server数据库,有很多的驱动可选,比较常用的: