【java】在java中用JDBC-ODBC桥及JDBC驱动程序连接数据库实例

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
* @author YanChengwei
*
*/
public class DBConnect {
/**
* @param args
*/
public static void main(String[] args) {
Connection con = null;// 连接
Statement stmt = null;// 执行语句
ResultSet rst = null;// 结果集

try {
   /*********用JDBC-ODBC桥连接oracle type 1***************/
//   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//   con = DriverManager.getConnection("jdbc:odbc:Oracledsn","myuser2","myuser2");//Oracledsn是dsn(数据源)的名称

  
   /********用JDBC驱动程序连接oracle type 2 and type 4***********/
   // 加载驱动程序
   Class.forName("oracle.jdbc.driver.OracleDriver");
  
   // 创建连接方法 1 用JDBC thin 驱动程序建立连接 type 2
   con = DriverManager.getConnection(
     "jdbc:oracle:thin:@192.168.1.110:1521:ORCL", "MYUSER2","myuser2");//注意:这句中的IP不能换成localhost,否则会出现Network Adepter 异常
  
   // 创建连接方法 2 用JDBC oci 驱动程序建立连接   type 4
//    "jdbc:oracle:oci8:@192.168.1.110:1521:ORCL",
//    "myuser1","myuser1");

   /** ***************** 创建执行语句方法 1 ******************* */
   stmt = con.createStatement();

   rst = stmt.executeQuery("select * from mytable2");

   // 输出结果
   while (rst.next()) {
    System.out.print(rst.getString("stuNumber") + " ");
    System.out.print(rst.getString("stuName") + " ");
    System.out.print(rst.getString("stuAddress") + " ");
    System.out.print(rst.getString("stuGender") + " ");
    System.out.println(rst.getString("stuAge") + " ");
   }

   // 关闭对象
   stmt.close();
   con.close();
} catch (ClassNotFoundException cnf) {
   System.out.println("没找到驱动程序");
   cnf.printStackTrace();

} catch (SQLException se) {
   se.printStackTrace();
}
}
}

java通过jdbc-odbc桥与mysql建立连接

一、打开mysql命令行,输入password root

在命令行,输入 create database mysqldata;

然后,在命令行,输入use mysqldata;

在命令行输入:create table student

(id int primary key,

name varchar(10),

mark int

);

显示Query ok,则创建成功。

二、添加数据源

打开“控制面板”,到“管理工具”,到“数据源“,但在系统DSN上没有MySql Driver。必须要安装MySql的ODBC。先打开http://www.mysql.com,打开download,找到MySql Connector/ODBC 5.1 Downloads,打开windows MSI Installer(x86),点击Download,即可下载MySql 的 ODBC。
安装完JDBC-ODBC桥之后,在刚才的”系统数据源“上,点击添加时,会显示,MsSQl ODBC 5。1 Driver,选中它,在出出的窗口中输入:数据源名字:mysqldata

Host/Server Name(or IP) :localhost

Database Name:mysaldata

Port(3306)

点击确定即创建好了。

三、在lomboz-eclipse 里面编辑类。

在eclipse,项目MyTest上的Java Resources:src上,点右键,创建一个java 类

package chapter10;
import java.sql.*;
public class MySqlJdbcOdbc {


public static void main(String[] args) {

new MySqlJdbcOdbc().launch();
}
public void launch(){
String driver="sun.jdbc.odbc.JdbcOdbcDriver";
String url="jdbc:odbc:mysqldata";
String query,name;
int mark;
Connection conn=null;
Statement statement=null;
ResultSet rs=null;

try{
Class.forName(driver);
}
catch(ClassNotFoundException e){
System.out.println("没有找到指定的驱动");
}
try{
conn=DriverManager.getConnection(url);
statement=conn.createStatement();
query="select * from student";
rs=statement.executeQuery(query);
while(rs.next())
{
name=rs.getString("name");
mark=rs.getInt("mark");
System.out.println("姓名: "+name);
System.out.println(" 成绩: "+mark);

}
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
try{
if(rs!=null) rs.close();
if(statement!=null) statement.close();
if(conn!=null) conn.close();

}
catch(SQLException e)
{
e.printStackTrace();
}
}


}
}
运行:run as :java application

四、上面的连接方式是JDBC——ODBC桥,下面的连接方式是,直接由MySql提供的JDBC桥进行数据库的连接方法。这里要用到JDBC桥,到http://www.mysql.com上下载所需要的驱动,找到downloads,在Drivers and Connectors下面,找到MySql Connector/J-for connecting to MySql from Java下载一个压缩包,注意:压缩包要下载.zip,这是为windows设置的JDBC驱动,而.tar.gz是为linux设置的JDBC驱动包。而解压后,在rec/ort/gjt/mm.mysql有一个Driver类文件,即是我们要导入到eclipse里面用的驱动

将下载的压缩包,解包后,如果我们想知道如何使用JDBC连接呢?想到找一下帮助文档。即找到解压开的文件夹,打开docs文件夹,找到其中的HTML文件,打开看,

import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; Connection conn = null; ... try { conn = DriverManager.getConnection("jdbc:mysql://localhost/test?" + "user=monty&password=greatsqldb"); // Do something with the Connection ... } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode());
}
 
将光标下拉,找到这样的话,The name of the class that implements java.sql.Driver in MySql Connector/J is com.mysql.jdbc.Driver.The org.gjt.mm.mysql.Driver class is also usable to remain backward-compatible with MM.MySql. You should use this class name when registering the driver,or when otherwise configuring software in use MySql connector/J.
The JDBC URL format for MySql Connector/J is as follows, with items in square brackets being optional:
jdbc:sql://[host][,failoverhost...][:port]/[database]
[?propertyName][=propertyValue][&propertyName2][=propertyValue2]....
If the hostname is not specified,it defaults to 127.0.0.1.if the port is not specified,it defaults to 3306,the default port number for MySql servers.
找到5。1。1Connectiong to MySql Using the DriverManager Interface
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class LoadDriver{
public static void main(String[] args){
try{
Clss.forName("com.mysql.jdbc.Driver").newInstance();
}
catch(Exception e){
//handle the error.
 
 
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; Connection conn = null; ... try { conn = DriverManager.getConnection("jdbc:mysql://localhost/test?" + "user=monty&password=greatsqldb"); // Do something with the Connection ... } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } 
 

java 导入外部jar文件,在工程根目录下,右击property,选择“Java Build Path",点击“Add external jars“,ok

或者,在工程根目录下,右击,选择“build path",在properties for MyTest窗口里,找到Libraries标鉴,点击Add External JARs,找到e:/安装软件/mysql安装程序夹/mysql-connector-java-5.1.7/mysql-connector-java-5.1.7-bin.jar,点击打开,Ok。

或者还有一个debug的这个的jar,那是带有调试的信息的,也可以。

import java.sql.*;
public class MySqlJdbc {


public static void main(String[] args) {

new MySqlJdbc().launch();
}
public void launch(){
//String driver="sun.jdbc.odbc.JdbcOdbcDriver";
//String url="jdbc:odbc:mysqldata";
String driver="org.gjt.mm.mysql.Driver";
String url="jdbc:mysql://localhost:3306/mysqldata?user=root;password=root";
String query,name;
int mark;
Connection conn=null;
Statement statement=null;
ResultSet rs=null;

try{
Class.forName(driver);

//Class.forName(driver).newInstance();
}
catch(ClassNotFoundException e){
System.out.println("没有找到指定的驱动");
}
try{
conn=DriverManager.getConnection(url);
statement=conn.createStatement();
query="select * from student";
rs=statement.executeQuery(query);
//String str="insert into student values('20021213','12','52')";
//statement.executeUpdate(str);
while(rs.next())
{
name=rs.getString("name");
mark=rs.getInt("mark");
System.out.println("姓名: "+name);
System.out.println(" 成绩: "+mark);

}
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
try{
if(rs!=null) rs.close();
if(statement!=null) statement.close();
if(conn!=null) conn.close();

}
catch(SQLException e)
{
e.printStackTrace();
}
}


}
}

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页