jdbc 用法

 

 

Test

public void demo1() throws Exception {

// 注册驱动

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

// 获得连接

String url = "jdbc:mysql://localhost:3306/day07";

String user = "root";

String password = "123";

Connection conn = DriverManager.getConnection(url, user, password);

// 获得发送sql的对象

Statement stmt = conn.createStatement();

// 执行sql 获得结果

String sql = "select * from user";

ResultSet rs = stmt.executeQuery(sql);

// 处理结果

while (rs.next()) {

int id = rs.getInt("id");

String username = rs.getString("username");

String pwd = rs.getString("password");

 

System.out.println(id + "::::" + username + "::::" + pwd);

}

// 释放资源

rs.close();

stmt.close();

conn.close();

}

 

==============================================================================================

@Test

public void select() {

// 需求: 根据用户名和密码查询用户信息

Connection conn = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

 

try {

// 获取连接

conn = JDBCUtils.getConnection();

// 获得发送sql的对象

String sql = "select * from user where username=? and password=?";

pstmt = conn.prepareStatement(sql);

// 设置参数

pstmt.setString(1, "wangwu");

pstmt.setString(2, "abc");

// 执行sql 获得结果

rs = pstmt.executeQuery();

// 处理结果

if (rs.next()) {

int id = rs.getInt("id");

String username = rs.getString("username");

String password = rs.getString("password");

 

System.out.println(id + ":::::::::" + username + ">>>>>" + password);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

JDBCUtils.release(conn, pstmt, rs);

}

}

 ==================================================================================

@Test

public void batch1() {

// 需求:编写一个批处理 程序,从建立数据库 day07_batch,切换到当前库 day07_batch,

// 建立数据表info(id,name),插入2条数据都执行

Connection conn = null;

Statement stmt = null;

 

try {

// 获得连接

conn = JDBCUtils.getConnection();

// 获得发送sql的对象

stmt = conn.createStatement();

 

// 将sql语句放到批处理缓冲区中

String sql = "create database day07_batch";

String sql2 = "use day07_batch";

String sql3 = "create table info(id int primary key auto_increment, name varchar(50))";

String sql4 = "insert into info values(null, '柳岩')";

String sql5 = "insert into info values(null, '刘亦菲')";

 

stmt.addBatch(sql);

stmt.addBatch(sql2);

stmt.addBatch(sql3);

stmt.addBatch(sql4);

stmt.addBatch(sql5);

 

// 执行批处理缓冲区中的sql语句

stmt.executeBatch();

 

} catch (Exception e) {

e.printStackTrace();

} finally {

JDBCUtils.release(conn, stmt);

}

}

posted @ 2017-08-15 14:56  ronniery  阅读(139)  评论(0编辑  收藏  举报