加载JDBC驱动程序
可使用Class.forName方法显式加载一个驱动程序。
如使用JDBC-ODBC桥:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
建立连接
DriverManager类的getConnection方法用于建立与某个数据源的连接。
如:
String url="jdbc:odbc:component";
Connection dataconn=
DriverManager.getConnection(url);
String url="jdbc:odbc:component";
Connection dataconn=
DriverManager.getConnection(url,"sa", "123");
连接数据库示例
package jdbcpkg;
import java.sql.*;
public class DBConn {
private Connection dataconn = null;
public DBConn() {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
dataconn = DriverManager.getConnection(“jdbc:odbc:MyJdbcOdbcSQL","sa","");
}
catch(Exception e){
System.out.println(e.toString());
}
public void setDataInsert(){
try{
Statement stmt = dataconn.createStatement();
stmt.executeUpdate("insert into jobs values('MyDesc',10,50)");
stmt.close();
System.out.println("数据插入成功!");
}
catch(Exception e){
System.out.println(e.toString());
}
}
public void setDataUpdate(int jobID){
try{
Statement stmt = dataconn.createStatement();
stmt.executeUpdate("update jobs set job_desc='OK Desc' where job_id="+jobID);
stmt.close();
System.out.println("数据修改成功!");
}
catch(Exception e){
System.out.println(e.toString());
}
}
public void setDataDelete(int jobID){
try{
Statement stmt = dataconn.createStatement();
stmt.executeUpdate("delete jobs where job_id = "+jobID);
stmt.close();
System.out.println("数据删除成功!");
}
catch(Exception e){
System.out.println(e.toString());
}
}
public int getDataUpdateCount(int min_lvl){
int intCount = -1;
try{
Statement stmt = dataconn.createStatement();
intCount = stmt.executeUpdate("update jobs set job_desc='Update Desc' where min_lvl =" + min_lvl);
stmt.close();
return intCount;
}
catch(Exception e){
System.out.println(e.toString());
return intCount;
}
}
public void getJobsData(){
try{
Statement stmt = dataconn.createStatement();
ResultSet rs = stmt.executeQuery("select * from jobs");
while(rs.next()){
System.out.println(rs.getInt("job_id")+" "+rs.getString("job_desc"));
System.out.println("-----------------------------------------------");
}
rs.close();
stmt.close();
}
catch(Exception e){
System.out.println(e.toString());
}
}
}
}
获取数据库信息示例
在DBConn.java中增加主函数main()及函数outDataMsg()如下:
public void outDataMsg(){
try{
DatabaseMetaData metaData = dataconn.getMetaData();
System.out.println(metaData.getURL());
System.out.println(metaData.getUserName());
System.out.println(metaData.isReadOnly());
System.out.println(metaData.getDatabaseProductName());
System.out.println(metaData.getDatabaseProductVersion());
System.out.println(metaData.getDriverName());
System.out.println(metaData.getDriverVersion());
}
catch(Exception e){
System.out.println(e.toString());
}
}
public static void main(String args[]){
DBConn c = new DBConn();
c.outDataMsg();
}