java实现odbc连接mysql_Java 连接数据库简单案例(JDBC-ODBC)

/**

* 作者:徐守威

* 功能:PreparedStatement演示.

* 1.PreparedStatement可以提高执行效率,因为它有预编译的功能

* 2.PreparedStatement可以防止sql注入,但是要求用?赋值的方式可以

* 时间:2012-11-8

*

*/

package com.test1;

import java.sql.*;

public class Test2 {

/**

* @param args

*/

public static void main(String[] args) {

//定义需要对象

PreparedStatement ps=null;

ResultSet rs=null;

Connection ct=null;

try{

//1.加载驱动

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

ct=DriverManager.getConnection("jdbc:odbc:mytest","sa","xushouwei");

/*ps=ct.prepareStatement("select * from dept where deptno=? and loc=?");

ps.setInt(1, 20);

ps.setString(2, "canada");

rs=ps.executeQuery();

while(rs.next()){

System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

}*/

//使用PreparedStatement添加一条记录

ps=ct.prepareStatement("insert into dept values(?,?,?)");

ps.setInt(1,50);

ps.setString(2, "安全部");

ps.setString(3, "南京");

//执行

int i=ps.executeUpdate();

if(i==1){

System.out.println("添加成功");

}else{

System.out.println("添加失败");

}

}catch(Exception e){

e.printStackTrace();

}finally{

//关闭资源

//关闭顺序:谁后创建谁先关闭

try {

//为了程序健壮

if(rs!=null){

rs.close();

}

if(ps!=null){

ps.close();

}

//sm.close();

if(ct!=null){

ct.close();

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值