以下的文章主要是介绍用java访问数据库DB2代码的实际操作步骤,首先我们是从创建表语句开始的,以下就是文章的主要内容描述,望大家在j对ava访问数据库DB2代码的实际操作步骤浏览之后会对其有更深的了解。
建表语句:
- create table test (id int,name varchar(20),password varchar(20))
插入一条数据:
- insert into test values (1,'zhu','yan')
java 代码:
- package com.test;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class ConnToDB2 {
//获得数据库连接
- public static Connection getconn(String location,String username,String password)
- {
- Connection conn = null;
- try {
- Class.forName("com.ibm.DB2.jcc.DB2Driver");
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- try {
- conn = DriverManager.getConnection(location,username,password);
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return conn;
- }
//查询数据
- public static void select()throws Exception
- {
- Connection conn = getconn("jdbc:DB2://192.168.10.100:50000/yan", "DB2inst1", "abc");
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery("select *from test");
- System.out.println("表中的数据如下:");
- while (rs.next())
- {
- System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
- }
- stmt.close();
- conn.close();
- }
//插入数据
- public static void insert()throws Exception
- {
- System.out.println("插入数据....");
- Connection conn = getconn("jdbc:DB2://192.168.10.100:50000/yan", "DB2inst1", "abc");
- Statement stmt = conn.createStatement();
- int rs = stmt.executeUpdate("insert into test values (3,'li','si')");
- stmt.close();
- conn.close();
- System.out.println();
- }
//跟新数据
- public static void update()throws Exception
- {
- System.out.println("更新数据....");
- Connection conn = getconn("jdbc:DB2://192.168.10.100:50000/yan", "DB2inst1", "abc");
- Statement stmt = conn.createStatement();
- int rs = stmt.executeUpdate("update test set password='kkk' where name='li'");
- stmt.close();
- conn.close();
- System.out.println();
- }
//删除数据
- public static void delete()throws Exception
- {
- System.out.println("删除数据....");
- Connection conn = getconn("jdbc:DB2://192.168.10.100:50000/yan", "DB2inst1", "abc");
- Statement stmt = conn.createStatement();
- int rs = stmt.executeUpdate("delete from test where name='li'");
- System.out.println();
- stmt.close();
- conn.close();
- }
- public static void main(String[] args)throws Exception {
- ConnToDB2 con = new ConnToDB2();
- con.select();
- con.insert();
- con.select();
- con.update();
- con.select();
- con.delete();
- con.select();
- }
- }
上述的相关内容就是对java实现访问数据库DB2代码的描述,希望会给你带来一些帮助在此方面。
【编辑推荐】