首页 > 其他分享 >jdbc 数据的增删改查的Statement Resultset PreparedStatement

jdbc 数据的增删改查的Statement Resultset PreparedStatement

时间:2022-09-29 15:03:13浏览次数:214  
标签:Exception jdbc rs Resultset 改查 sql null e2 con

完成数据库的连接,就马上要对数据库进行增删改查操作了;先来了解一下Statement

通过JDBC插入数据 (这里提供一个查找和插入方法)
Statement:用于执行sql语句的对象;
*1.通过Connection 的creatStatement()方法来获取;
*2.通过executeUpdate(sql) 可以执行SQL语句
*3.传入的SQL可以是insert update delete,但是不能是select;
* 注意:在使用后要关闭connection和statement(在finally中关闭)
* 关闭的顺序:先关statement ; 后关 connection
@Test
public void testStatement()throws Exception{
//1.获取数据库连接
Connection conn = null;
Statement st = null;
try {
conn = getConnection();//参看最底下的附录(获取连接)
//2.准备插入的sql
String sql ="insert into contacts(name,address,phone)"+"value('xyz','abc','abc')";
//3.执行插入
//获取sql的statement对象:Connection的createStatement()方法来获取
st = conn.createStatement();
//调用statement对象的executeUpdate(sql)对象,插入sql语句
st.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
}finally{
try{
if(st !=null)
//关闭Statement 对象
st.close();
}catch (Exception e) {
e.printStackTrace();
}finally{
//关闭连接
if(conn !=null)
conn.close();
}

} }
/**
* ResultSet:结果集,封装了使用JDBC进行查询的接口
* 1.调用Statement 对象的executeQuesry(sql)可以得到结果集
* 2.返回一张数据表,有指针指向数据表的第一行的前面
* 3.可以调用next方法检测下一行是否有效,若有效返回true且指针下移
* 4.当指针对到一行时,可以通过getxxxx(index)或者getxxx(cloumName);
* 获取每一列的值:getInt(1),getString("name")
* @throws Exception
*/
@Test
public void testResultSet() throws Exception{
//获取Id=19的记录值,并且每条打印
Connection con = null;
ResultSet rs = null;
Statement st = null;
try {
//1.获取connection
con = JdbcTools.getConnection();//JdbcTools.getConnection()同附录的方法
//2.获取Statement
st = con.createStatement();
//3.准备sql
String sql = "select * from contacts where id=19";
//4.获取ResultSet
rs = st.executeQuery(sql);
//5.处理ResultSet
if(rs.next()){//如果是多条记录,把if改成while
int id = rs.getInt(1);//第一列
String name = rs.getString("name");
String address = rs.getString(3);
System.out.println(id);
System.out.println(name);
System.out.println(address);
}
//6.关闭
} catch (Exception e) {
e.printStackTrace();
}finally{
JdbcTools.release(rs, st, con);//方法见附录
}
}
//以上提供了插入和查询方法
*********************************************************************************************************************
这里我们在来了解一个PreparedStatement方法,可以对比Stetement
/**
* PreparedStatement是Stetement的子接口;
*preparedStatement:使用statement,sql需要拼接;
*PerparedStatement:String sql="insert into contacts(name,address,phone) value(?,?,?)"
*Statement:String sql = "insert into contacts(name,address,phone)"+"value('nn'+'121'+'1212')";
*1.创建preparedStatement:
*2.调动PreparedStatement的setxxx(int index,object value),设置占位符的值
*这里index从1开始
*3.执行sql语句:executeQuery()或者executeUpdate(),前者是查询,后者是更新
*注意,执行时不再需要闯入sql语句
*
*好处:1防止SQl注入,即防止拼接过程中有加入其它东西,例如有OR···,这样,sql就可以正确执行;2提高性能;3····
*
* @throws Exception
*/
@Test
public void testPreparedStatement() throws Exception {
Connection con = null;
PreparedStatement p = null;
ResultSet rs = null;
try {
con = JdbcTools.getConnection();
String sql = " insert into contacts(name,address,phone)values(?,?,?)";
p = con.prepareStatement(sql);
p.setString(1, "tom");
p.setString(2, "zhejiang");
p.setString(3, "15988324290");
p.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally{
JdbcTools.releaseDB(rs, p, con);
}

}

附上
getConnection() throws Exception{
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;

//读取类路径下的properties
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties p = new Properties();
p.load(in);
driverClass=p.getProperty("driver");
jdbcUrl = p.getProperty("jdbcUrl");
user = p.getProperty("user");
password = p.getProperty("password");


Driver driver = (Driver) Class.forName(driverClass).newInstance();//实例化
Properties info = new Properties();
info.put("user",user);
info.put("password",password);
Connection connection = driver.connect(jdbcUrl, info);
return connection;
}


public static void release(ResultSet rs, Statement statement ,Connection con) throws Exception{

if(rs != null){

try {

rs.close();

} catch (Exception e2) {

e2.printStackTrace();

}



}



if(statement !=null){

try {

statement.close();

} catch (Exception e2) {

e2.printStackTrace();

}

}



if(con!=null){

try {

con.close();

} catch (Exception e2) {

e2.printStackTrace();

}

}

}

public static void releaseDB(ResultSet rs, PreparedStatement statement ,Connection con) throws Exception{
if(rs != null){
try {
rs.close();
} catch (Exception e2) {
e2.printStackTrace();
}

}

if(statement !=null){
try {
statement.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}

if(con!=null){
try {
con.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}

需要导入的包
mysql-connector-java-5.1.34.jar


我从来不相信什么懒洋洋的自由。我向往的自由是通过勤奋和努力实现的更广阔的人生。
我要做一个自由又自律的人,靠势必实现的决心认真地活着。

标签:Exception,jdbc,rs,Resultset,改查,sql,null,e2,con
From: https://blog.51cto.com/u_10632206/5722956

相关文章

  • (五)JPA - 原生SQL实现增删改查
    6、原生SQLJPA除了对JPQL提供支持外,还对原生SQL语句也提供了支持。下面小节一起来看看吧。6、1查询单个示例代码:@TestpublicvoidgetSingle(){......
  • Spring JDBC 数据访问
    SpringJDBC数据访问SpringJDBC是Spring所提供的持久层技术,它的主要目标是降低使用JDBCAPI的门槛,以一种更直接,更简介,更简单的方式使用JDBCAPI,在SpringJDBC里,仅......
  • maven 加载依赖sqljdbc4报错
    错误现象:MavenFailuretofindcom.microsoft.sqlserver:sqljdbc4:jar:4.0解决方法:1.下载对应的sqljdbc4.jar包2.shell窗口执行命令mvninstall:install-file-D......
  • day04 --> (JDBC基本概念、快速入门、对JDBC中各个接口和类详解)
    一、JDBC:1、概念:JavaDataBaseConnectivity -->Java数据库连接,Java语言操作数据库本质:官方(sun公司)定义的一套操作所有关系型数据库的规则,即接口。各个数据库厂商去实......
  • 解决Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver cl
    解决Loadingclass`com.mysql.jdbc.Driver'.Thisisdeprecated.Thenewdriverclassis`com.mysql.cj.jdbc.Driver'.Thedriverisautomaticallyregisteredviat......
  • JavaWeb 6 JDBC 常用API
         ......
  • JavaWeb5 JDBC
       packagecom.itheima.jdbc;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.SQLOutput;importjava.sql.Statement;publi......
  • JDBC 尚硅谷 days01-数据库连接方式
    1.JDBC(JavaDatabaseConnectivitu):是一个独立于特定数据库管理系统、通用的SQL数据库存储和操作的公共接口;2.JDBC接口包括两个层次面向应用的API:JavaAPI,抽象接口,......
  • C#数据库增删改查
    C#链接数据库增删改查的例子 以users表为例,有三个字段,自增长的编号id,int类型;名称name,nvarchar类型,密码pwd,nvarchar类型首先在vs2005中引入usingSystem.Data.SqlClien......
  • 今日内容 序列化与反序列化 实现增删改查
    APIView的基本使用drf:是一个第三方的app,只能在djagno上使用安装了drf后,导入一个视图类APIView,所有后期要使用drf写视图类,都是继承APIView及其子类例:获取所有图书接......