- 论坛徽章:
- 0
|
Java应用访问数据库最直接的方式就是直接访问JDBC API,JDBC是Java Database Connectivity的缩写。java.sql包则提供了JDBC的API,其中常用的接口和类有:
- DriverManager:驱动程序管理器,负责创建数据库连接。
- Connection:代表数据库连接。
- Statement:负责执行SQL语句。
- PrepareStatement:负责执行SQL语句,具有预定义SQL语句的功能。
- ResultSet:代表SQL查询语句的查询结果集。
各类数据库连接代码:
1、Oracle8/8i/9i数据库(thin模式)
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
String url="jdbc:oracle:thin:@localhost:1521:orcl";
//orcl为数据库的SID
String user="tt";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);
2、DB2数据库
Class.forName("com.ibm.db2.jdbc.app.DB2Driver").newInstance();
String url="jdbc:db2://localhost:5000/yourDB";
//yourDB为你的数据库名
String user="tt";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);
3、Sql Server2000数据库
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=yourDB";
//yourDB为数据库
String user="sa"; //连接用户
String password=""; //连接密码
Connection conn= DriverManager.getConnection(url,user,password);
4、Sybase数据库
Class.forName("com.sybase.jdbc.SybDriver").newInstance();
String url =" jdbc:sybase:Tds:localhost:5007/yourDB";
//yourDB为你的数据库名
Properties sysProps = System.getProperties();
SysProps.put("user","userid");
SysProps.put("password","user_password");
Connection conn= DriverManager.getConnection(url, SysProps);
5、MySQL数据库
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url ="jdbc:mysql://localhost:3306/yourDB?user=root&password=123&useUnicode=true&characterEncoding=UTF-8"
//yourDB为数据库名
Connection conn= DriverManager.getConnection(url);
6、access数据库直连用ODBC的
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
String url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ="+application.getRealPath("/Data/ReportDemo.mdb");
Connection conn = DriverManager.getConnection(url,"","");
Statement stmtNew=conn.createStatement() ;
JDBC在程序中的使用:
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class JDBC {
private String url = "jdbc:mysql://localhost:3306/db";
private String user="root";
private String pwd="123";
public JDBC() throws ClassNotFoundException{
Class.forName("com.mysql.jdbc.Driver");
}
public Connection getConnection() throws SQLException{
return java.sql.DriverManager.getConnection(url, user, pwd);
}
public void saveObj(Object obj){
Connection con = null;
PreparedStatement stmt = null;
try{
con=this.getConnection();
con.setAutoCommit(false);
stmt = con.prepareStatement("sql 语句");
stmt.setString(0,"值"); //0为"索引"
stmt.execute();
con.commit();
}catch(Exception e){
try{
con.rollback();
}catch(SQLException se){
se.printStackTrace();
}
e.printStackTrace();
}
}
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/82195/showart_1432151.html |
|