
正文
java连接jdbc代码 javajdbc连接oracle
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
Java中如何实现与后台数据库的连接?
用JAVA连接数据库主要有两种方式java连接jdbc代码,一是用JDBC-ODBC桥来连接java连接jdbc代码,二是用相关厂商提供的相应驱动程序来连接,首先谈谈第一种连接。 \x0d\x0a\x0d\x0aJDBC-ODBC桥接器是用JdbcOdbc.Class和一个用于访问ODBC驱动程序的本地库实现的。对于WINDOWS平台,该本地库是一个动态连接库DLL(JDBCODBC.DLL)。 \x0d\x0a\x0d\x0a由于JDBC在设计上与ODBC很接近。在内部,这个驱动程序把JDBC的方法映射到ODBC调用上,这样,JDBC就可以和任何可用的ODBC驱动程序进行交互了。这种桥接器的优点是,它使JDBC目前有能力访问几乎所有的数据库。通行方式如图所示: \x0d\x0a\x0d\x0a应用程序---JDBC API---JDBC-ODBC---ODBC API---ODBC层---数据源 \x0d\x0a\x0d\x0a具体操作方法为: \x0d\x0a\x0d\x0a首先打开控制面板的管理工具,打开数据源(ODBC),在用户DSN里面添加数据源(即你要连接的数据库的名字),在这里假定连接SQL SERVER 2000的GoodsSupply数据库。名称填写你要连接的数据库的名称(GoodsSupply),然后逐步设置,如果选用了使用SQL-SERVER密码认证的话,就要输入相应的用户名及密码连接到数据库。一路下一步设置完成。 \x0d\x0a\x0d\x0a在JAVA里面编写程序进行测试,在这里我的程序是让用户输入任意的表名与与列名,把该列的所有数据输出。源代码如下: \x0d\x0a\x0d\x0aimport java.io.BufferedReader; \x0d\x0aimport java.io.InputStreamReader; \x0d\x0aimport java.sql.*; \x0d\x0a\x0d\x0apublic class ODBCBridge { \x0d\x0a\x0d\x0apublic static void main(String[] args) { \x0d\x0aString url="jdbc:odbc:GoodsSupply"; \x0d\x0aStatement sm=null; \x0d\x0aString command=null; \x0d\x0aResultSet rs=null; \x0d\x0aString tableName=null; \x0d\x0aString cName=null; \x0d\x0aString result=null; \x0d\x0aBufferedReader input=new BufferedReader(new InputStreamReader(System.in)); \x0d\x0atry { \x0d\x0atry { \x0d\x0aClass.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //加载驱动 \x0d\x0a}catch(ClassNotFoundException e){ \x0d\x0aSystem.out.println("Can not load Jdbc-Odbc Bridge Driver"); \x0d\x0aSystem.err.print("ClassNotFoundException:"); \x0d\x0aSystem.err.println(e.getMessage()); \x0d\x0a} \x0d\x0aConnection con=DriverManager.getConnection(url,"USER","PASSWORD"); //使用SQL-SERVER2000认证 \x0d\x0aDatabaseMetaData dmd=con.getMetaData(); //DMD为连接的相应情况 \x0d\x0aSystem.out.println("连接的数据库:"+dmd.getURL()); \x0d\x0aSystem.out.println("驱动程序:"+dmd.getDriverName()); \x0d\x0asm=con.createStatement(); \x0d\x0aSystem.out.println("输入表名"); \x0d\x0atableName=input.readLine(); \x0d\x0awhile(true) { \x0d\x0aSystem.out.println("输入列名(为空时程序结束):"); \x0d\x0acName=input.readLine(); \x0d\x0aif(cName.equalsIgnoreCase("")) \x0d\x0abreak; \x0d\x0acommand="select "+cName+" from "+tableName; \x0d\x0ars=sm.executeQuery(command); //执行查询 \x0d\x0aif(!rs.next()) \x0d\x0aSystem.out.println("表名或列名输入有误"); \x0d\x0aelse { \x0d\x0aSystem.out.println("查询结果为:"); \x0d\x0ado \x0d\x0a{ \x0d\x0aresult=rs.getString(cName); \x0d\x0a//数据库语言设置为中文,不用转换编码 \x0d\x0a//result=new String(result.getBytes("ISO-8859-1"),"GB2312"); \x0d\x0aSystem.out.println(result); \x0d\x0a}while(rs.next()); \x0d\x0a} \x0d\x0a} \x0d\x0a}catch(SQLException ex) { \x0d\x0aSystem.out.println("SQLException:"); \x0d\x0awhile(ex!=null) { \x0d\x0aSystem.out.println("Message:"+ex.getMessage()); \x0d\x0aex=ex.getNextException(); \x0d\x0a} \x0d\x0a}catch(Exception e) { \x0d\x0aSystem.out.println("IOException"); \x0d\x0a} \x0d\x0a} \x0d\x0a}
相关问答
Q1: java连接数据库的代码
用这个类吧.好的话,给我加加分.
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();
}
}
Q2: 用Java怎样访问数据库,用什么代码?
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数据库,有很多的驱动可选,比较常用的:
Q3: 利用java代码,编写JDBC连接数据库新增员工信息的步骤. 员工信息表:t_emp(id int?
第一步:新建数据库
连接的是本地localhost,新建一个新的数据库名是jdbctest
然后建表t_emp
不会的话可通过执行下方的sql语句建表
CREATE TABLE `t_emp` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`salary` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
第二步:新建java项目
新建完以后添加mysql驱动的jar包,jar包自己下载
在项目上右键鼠标属性,然后
添加jar包,我这里已经加载过了
第三步:编写代码
package com.gf;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class Test {
public static void main(String[] args) throws Exception {
int flag=0;
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
Connection conn=(Connection) DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbctest?user=rootpassword=123456useUnicode=truecharacterEncoding=UTF-8");
//3.创建statement
Statement sm=(Statement) conn.createStatement();
//4.执行sql语句
flag=sm.executeUpdate("insert into t_emp(name,salary) values('菲菲',34.9)");
if(flag!=0) {
System.out.println("员工信息增加成功");
}else {
System.out.println("添加失败");
}
}
}
注意点:
---------------------------------------------------------------------------------
DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbctest?user=rootpassword=123456useUnicode=truecharacterEncoding=UTF-8");
这里需要修改自己本机的连接信息,不然会出现连接失败
最后的执行结果
Q4: java中使用JDBC连接数据库的步骤是什么?
注册驱动
Class.forname("com.mysql.jdbc.Driver");//这是连接mysql数据库的驱动
获取数据库连接
java.sql.Connection conn=java.sql.DriverManager.getConnection(); 3.获取表达式
java.sql.Statement stmt=conn.createStatement("jdbc:mysql://localhost/test?
useUnicode=truecharacterEncoding=GBK","root","null");//三个参数分别是数据库连接的URL,
用户名,密码 4.执行SQL
java.sql.ResultSet rs=stmt.executeQuery("select * from user"); 5.显示结果集里面的数据
while(rs.next()){
System.out.println(rs.getInt(1));
System.out.println(rs.getString("username"));
System.out.println(rs.getString("password"));
System.out.pringln();
}//执行插入语句
//stmt.executeUpdate("insert into user values(1,'中文','345')");
释放资源
rs.close();
stmt.close();
conn.close();
java连接jdbc代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于javajdbc连接oracle、java连接jdbc代码的信息别忘了在本站进行查找喔。







