您的位置:首页 > 编程语言 > Java开发

Java使用jdbc操作Mysql数据库

2011-08-10 11:48 736 查看
Java使用jdbc操作mysql数据库

一、连接数据库

1. 加载驱动,首先应该引入jar包,如果你使用shell(如cmd命令下的javac)来编译的话,你应该确保classpath中加入了jar包的路径。如果你使用eclipse的话,你要在项目中配置jar包。

2. 使用jdbc加载驱动:

Class.forName(驱动类);

Mysql的驱动类:org.gjt.mm.mysql.Driver

3. 建立Connection对象:

Connection conn=null;

conn=DriverManager.getConnection(DBURL,DBUSER,DBPWD);

mysql的连接ULR形如: jdbc:mysql://localhost:3306/test

4. 连接完成,当操作完成后,应确保conn关闭:

conn.close();

二、读取数据

1. 建立Connection对象

2. 使用Connection对象的createStatement方法建立Statement对象

Statement st=conn.CreateStatement();

3. 使用ResultSet保存Statement的executeQuery方法返回的数据:

ResultSet rs=null;

rs=st.executeQuery(sql);

4. 使用ResultSet的next方法来判断数据是否存在,使用ResultSet的getXXX(字段名|索引)方法来获取数据(注意,如果使用索引,索引从1开始)

while(rs.next()){

System.out.println(rs.getInt(1));

}

5.依次关闭ResultSet

关闭Statement

关闭Connection

三、更新数据

1.建立Connection对象

2.使用Connection对象的preparedStatement的方法建立PreparedStatement对象

PreparedStatemnet pre=conn.PreparedStatement(“insert into table(name) values(?)”);

3.使用PreparedStatement对象的setXXX方法,附加值

pre.SetString(1,”hi”);

5. 使用pre对象的executeUpdate方法更新数据

pre.executeUpdate();

6. 依次关闭PreparedStatement对象和Connection对象

四、使用Statement更新固定数据

Connection conn=null;

Class.forName(DBDRIVER);

conn=DriverManager.getConnection(DBURL,DBUSER,DBPWD);

Statement statement=conn.createStatement();

String sql="delete from test where id=1974";

statement.executeUpdate(sql);

statement.close();

conn.close();

五、批处理

使用PreparedStatement的addBatch方法增加批处理,使用PreparedStatement的executeBatch()来更新数据。示例代码如下:

Connection conn=null;

Class.forName(DBDRIVER);

conn=DriverManager.getConnection(DBURL,DBUSER,DBPWD);

PreparedStatement pre=conn.prepareStatement("insert into test"+

"(name,age) values(?,?)");

for(int i=1;i<10;i++){

pre.setString(1, "guoxu"+i);

pre.setInt(2, 100+i);

pre.addBatch();

}

int[] t=pre.executeBatch();

System.out.println(t.length);

pre.close();

conn.close();

六、事务处理

事务处理是指提交一批数据,如果成功,则提交,如果失败则可以回滚。事物处理首先需要将自动提交设为false.如:conn.setAutoCommit(false);然后try,如果成功,则conn.commit();如果失败,则conn.rollback();

但需要注意的是,对事务的处理同样需要数据表的支持,mysql的myisam不支持事务,innodb支持事务。所以需要将数据表类型改为InnoDB才可以支持事务。

示例代码如下:

Connection conn=null;

Class.forName(DBDRIVER);

conn=DriverManager.getConnection(DBURL,DBUSER,DBPWD);

conn.setAutoCommit(false);

Statement pre=conn.createStatement();

try{

pre.addBatch("insert into test(name,age) values('guoxu',25)");

pre.addBatch("insert into test(name,age) values('lisi',25)");

pre.addBatch("insert into test(name,age) values('wagnwu',25)");

pre.addBatch("insert into test(name,age) values('zhaoliu',25)");

int[] l=pre.executeBatch();

System.out.println(l.length);

conn.commit();

}catch(Exception e){

conn.rollback();

}

pre.close();

conn.close();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: