java-编码笔记-PreparedStatement实验

 概要: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');

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值