概要:PreparedStatement实验(就是一个处理sql中参数的对象)。
1.代码
package com.deliver.ms;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class PrepareStatementTest {
public static void main(String[] args) {
System.out.println("PrepareStatement 数据插入实验");
insert();
}
static void insert() {
// TODO Auto-generated method stub
// 驱动程序名
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名scutcs
String url = "jdbc:mysql://127.0.0.1:3306/xjc_db_test?useUnicode=true&characterEncoding=utf8&useSSL=false&zeroDateTimeBehavior=convertToNull";
// MySQL配置时的用户名
String user = "root";
// MySQL配置时的密码
String password = "123456";
try {
// 加载驱动程序
Class.forName(driver);
// 连续数据库
Connection conn = DriverManager.getConnection(url, user, password);
String insertSql = "insert into tb(id,v1) values(?,?)";
PreparedStatement pstmt = conn.prepareStatement(insertSql);
pstmt.setInt(1, 2);
pstmt.setString(2, "value");
int no = pstmt.executeUpdate();
System.out.println(no);
String selectSql = "select * from tb";
PreparedStatement pstmt2 = conn.prepareStatement(selectSql);
ResultSet rs = pstmt2.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String v1 = rs.getString("v1");
System.out.println("id:"+id+" v1:"+v1);
}
} catch (ClassNotFoundException e) {
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. 运行结果
PrepareStatement 数据插入实验
1
id:2 v1:value
3.创建数据库的脚本
create table tb(id int,v1 varchar(16));
select * from tb;
insert into tb(id,v1) values(1,'value1');