Eclipse中java向数据库中添加数据,更新数据,删除数据
前面详细写过如何连接数据库的具体操作,下面介绍向数据库中添加数据。
注意事项:如果参考下面代码,需要
改包名,数据库名,数据库账号,密码,和数据表(数据表里面的信息)
1 package com.ningmeng; 2 3 import java.sql.*; 4 5 /** 6 * 1:向数据库中添加数据 7 * @author biexiansheng 8 * 9 */ 10 public class Test01 { 11 12 public static void main(String[] args) { 13 try { 14 Class.forName("com.mysql.jdbc.Driver");//加载数据库驱动 15 System.out.println("加载数据库驱动成功"); 16 String url="jdbc:mysql://localhost:3306/test";//声明数据库test的url 17 String user="root";//数据库的用户名 18 String password="123456";//数据库的密码 19 //建立数据库连接,获得连接对象conn(抛出异常即可) 20 Connection conn=DriverManager.getConnection(url, user, password); 21 System.out.println("连接数据库成功"); 22 //生成一条mysql语句 23 String sql="insert into users(username,password,age,sex) values('小别','123456',22,0)"; 24 Statement stmt=conn.createStatement();//创建一个Statement对象 25 stmt.executeUpdate(sql);//执行sql语句 26 System.out.println("插入到数据库成功"); 27 conn.close(); 28 System.out.println("关闭数据库成功"); 29 } catch (ClassNotFoundException e) { 30 // TODO Auto-generated catch block 31 e.printStackTrace(); 32 }// 33 catch (SQLException e) { 34 // TODO Auto-generated catch block 35 e.printStackTrace(); 36 } 37 38 } 39 40 }
详细运行结果
这样就可以完美插入数据,增删改查第一步完美解决。
简单介绍一下所使用的知识点:
在java程序中一旦建立了数据库的连接,就可以使用Connection接口的createStatement()方法来获得statement对象
然后通过excuteUpdate()方法来执行sql语句,就可以向数据库中添加数据了。
1:createStatement()方法是Connection接口的方法,用来创建Statement对象
2:Connection接口代表和特定的数据库连接,要对数据库中数据表的数据进行操作,首先要获取数据库连接。
3:Statement接口用于创建向数据库中传递SQL语句的对象,该接口提供了一些方法可以实现对数据库的常用操作。
4:Statement接口中的excuteUpdate()方法执行给定的SQL语句,该语句可以是INSERT,UPDATE,DELETE语句。
第二种方法
使用PreparedStatement接口向mysql数据库中插入数据
1 package com.ningmeng; 2 3 import java.sql.*; 4 5 /** 6 * 1:使用PreparedStatement接口来执行插入语句 7 * 8 * @author biexiansheng 9 * 10 */ 11 public class Test02 { 12 13 public static void main(String[] args) { 14 // TODO Auto-generated method stub 15 try { 16 Class.forName("com.mysql.jdbc.Driver");//加载数据库驱动 17 System.out.println("加载数据库驱动成功"); 18 String url="jdbc:mysql://localhost:3306/test";//声明数据库test的url 19 String user="root";//数据库用户名 20 String password="123456";//数据库密码 21 //建立数据库连接,获得连接对象conn 22 Connection conn=DriverManager.getConnection(url, user, password); 23 System.out.println("连接数据库驱动成功"); 24 //生成一条SQL语句 25 String sql="insert into users(username,password,age,sex) values(?,?,?,?)"; 26 PreparedStatement ps=conn.prepareStatement(sql);//创建一个Statement对象 27 ps.setNString(1,"lisi");//为sql语句中第一个问号赋值 28 ps.setString(2,"123456");//为sql语句中第二个问号赋值 29 ps.setInt(3,24);//为sql语句第三个问号赋值 30 ps.setInt(4,2);//为sql语句的第四个问号赋值 31 ps.executeUpdate();//执行sql语句 32 conn.close();//关闭数据库连接对象 33 System.out.println("关闭数据库连接对象"); 34 } catch (ClassNotFoundException e) { 35 // TODO Auto-generated catch block 36 e.printStackTrace(); 37 } catch (SQLException e) { 38 // TODO Auto-generated catch block 39 e.printStackTrace(); 40 } 41 42 43 } 44 45 }
由于刚才不小心多执行了一遍第一个程序,所以多了一行id==7的,特此注释一下
1:PreparedStatement接口继承Statement,用于执行动态的SQL语句,通过PreparedStatement实例执行SQL语句,将被预编译并且保存到PreparedStatement实例中,从而可以反复的执行该SQL语句。
2:PreparementStatement接口中的方法,如executeUpdate在此PrepareStatement对象中执行sql语句,该sql语句必须是一个INSERT.UPDATE,DELETE语句,或者是没有返回值的DDL语句。
3:setString(int pIndex,String str)将参数pIndex位置上设置为给定的String类型的参数,俗语就是在第几个位置写上符合的数据类型
setInt(int pIndex,int x)
其他的都类似,不作多叙述
更深层次的理解JDBC对java程序和数据库之间的操作
JDBC技术的常用类和接口
必须搞明白这些关系,不能只会写代码,理解其含义。
(1):必须清楚,JDBC是一种可用于执行SQL语句的JAVA API(Application Programming Interface,应用程序设计接口),是连接数据库和java应用程序的一个纽带。
(2):DriverManager类用来管理数据库中的所有驱动程序,是JDBC的管理层,作用与用户和驱动程序之间,跟踪可用的驱动程序,并在数据库的驱动程序之间建立连接。
DriverManager类最常用的方法是
getConnection(String url,String user,String password);
(3):Connection接口代表与特定的数据库的连接,要对数据表中的数据进行操作,首先要获取数据库的连接。Connection实例就像在应用程序与数据库之间开通了一条通道。
可通过DriverManager类的getConnection()方法获取Connection实例。
比如:
Connection conn=DriverManager.getConnection(url, user, password);
Statement stmt=conn.createStatement();//创建一个Statement对象
Connection接口常用的方法是:
createStatement()创建Statement对象
close()立即释放此Connection对象的数据库和JDBC资源,而不是等待它们被自动释放。
(4):Statement接口用于创建向数据库中传递SQL语句的对象,该接口提供了一些方法可以实现对数据库的常用操作。(Statement接口用于执行静态SQL语句,并返回它所生成结果的对象)
Statement接口常用的方法
execute(String sql);执行静态的SELECT语句,该语句可能返回多个结果集
executeQuery(String sql);执行给定的SQL语句,该语句返回单个ResultSet对象。
executeUpdate()执行给定的SQL语句,该语句可以为INSERT,UPDATE,DELETE语句。
close()释放Statement实例占用的数据库和JDBC资源。
(5):PreparedStatement接口继承了Statement接口,用于执行动态的SQL语句,通过PreparedStatement实例执行的sql语句,将被预编译并保存到PreparedStatement实例中,从而可以反复的执行该SQL语句。
PreparedStatement接口的常用方法。
execute();在此PreparedStatement对象中执行SQL语句,该语句可以是任何类型的SQL语句。
executeQuery()在此PreparedStatement对象中执行SQL查询语句,返回结果为查询结果集ResultSet对象。
executeUpdate()在此PreparedStatement对象中执行SQL语句,该语句必须是一个INSERT,UPDATE,DELETE语句。或者是没有返回值的DDL语句。
close()释放Statement实例占用的数据库和JDBC资源。
(6):ResultSet接口类似与一个临时表,用来暂时存放数据库查询操作所获得的结果集,
下面写几个程序更深层次的理解一下JDBC作为连接数据库的JAVA程序纽带
1:首先封装了通用的一些东西,然后通过引入调用(需要注意的是包名,类名,mysql数据库账号,密码,数据库名,数据表名,字段等等。)
1 package com.util; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.SQLException; 6 7 public class Dbutil { 8 9 private static String url="jdbc:mysql://localhost:3306/db_person";//生命数据库的url(地址) 10 private static String user="root";//数据库账号 11 private static String password="123456";//数据库密码 12 private static String driver="com.mysql.jdbc.Driver";//数据库的驱动 13 14 /** 15 * 16 * @return 17 * @throws Exception 18 */ 19 public Connection getCon() throws Exception{ 20 Class.forName(driver);//加载数据库驱动 21 Connection con=DriverManager.getConnection(url, user, password); 22 //建立数据库的连接,获得连接对象con 23 return con; 24 } 25 26 /** 27 * 28 * @param con 29 * @throws Exception 30 */ 31 public void close(Connection con) throws Exception{ 32 if(con!=null){ 33 con.close(); 34 } 35 } 36 37 38 }
1 package com.ningmeng; 2 3 import java.sql.Connection; 4 import java.sql.Statement; 5 6 import com.util.Dbutil; 7 8 public class Test { 9 10 public static void main(String args[]) throws Exception { 11 Dbutil db=new Dbutil(); 12 String sql="insert into db_book values(null,'javaweb',888,'小别',1)";//生成一条sql语句 13 Connection con=db.getCon();//获取数据库的连接 14 Statement stmt=con.createStatement();//创建一个Statement连接 15 int result=stmt.executeUpdate(sql);//执行sql语句 16 System.out.println("执行了"+result+"数据"); 17 stmt.close();//关闭顺序是先关闭小的,后关闭大的 18 con.close(); 19 20 } 21 }
2:数据库的插入一般都是从前台获取的,上面这个例子不是很好,下面举例另一种方式。
(插入数据时使用拼接)同样引用上面封装的通用的一些东西!!!
1 package com.ningmeng; 2 3 import java.sql.Connection; 4 import java.sql.Statement; 5 6 import com.util.Dbutil; 7 8 public class Test2 { 9 10 private static Dbutil db=new Dbutil(); 11 private static int add(String name,float price,String author,int bookTypeId) 12 throws Exception{ 13 Connection con=db.getCon(); 14 String sql="insert into db_book values(null,'"+name+"',"+price+",'"+author+"',"+bookTypeId+")"; 15 Statement stmt=con.createStatement();//创建一个Statement连接 16 int result=stmt.executeUpdate(sql);//执行sql语句 17 db.close(stmt,con); 18 return result; 19 } 20 public static void main(String[] args) throws Exception { 21 // TODO Auto-generated method stub 22 int result=add("java",888,"小卡",1); 23 if(result==1){ 24 System.out.println("添加成功"); 25 }else{ 26 System.out.println("添加失败"); 27 } 28 29 } 30 31 }
(可以发现已经添加成功了)
3:下面使用面向对象的思想传入数据(实现的时候和上面的一同完成操作,)
1 package com.ningmeng; 2 3 public class Book { 4 5 private String name; 6 private float price; 7 private String author; 8 private int bookTypeId; 9 public String getName() { 10 return name; 11 } 12 public void setName(String name) { 13 this.name = name; 14 } 15 public float getPrice() { 16 return price; 17 } 18 public void setPrice(float price) { 19 this.price = price; 20 } 21 public String getAuthor() { 22 return author; 23 } 24 public void setAuthor(String author) { 25 this.author = author; 26 } 27 public int getBookTypeId() { 28 return bookTypeId; 29 } 30 public void setBookTypeId(int bookTypeId) { 31 this.bookTypeId = bookTypeId; 32 } 33 public Book(String name, float price, String author, int bookTypeId) { 34 super(); 35 this.name = name; 36 this.price = price; 37 this.author = author; 38 this.bookTypeId = bookTypeId; 39 } 40 41 42 43 44 }
1 package com.ningmeng; 2 3 import java.sql.Connection; 4 import java.sql.Statement; 5 6 import com.util.Dbutil; 7 8 public class Test2 { 9 10 private static Dbutil db=new Dbutil(); 11 12 private static int add2(Book book) throws Exception{ 13 Connection con=db.getCon(); 14 String sql="insert into db_book values(null,'"+book.getName()+"',"+book.getPrice()+",'"+book.getAuthor()+"',"+book.getBookTypeId()+")"; 15 Statement stmt=con.createStatement();//创建一个Statement连接 16 int result=stmt.executeUpdate(sql);//执行sql语句 17 db.close(stmt,con); 18 return result; 19 } 20 21 private static int add(String name,float price,String author,int bookTypeId) 22 throws Exception{ 23 Connection con=db.getCon(); 24 String sql="insert into db_book values(null,'"+name+"',"+price+",'"+author+"',"+bookTypeId+")"; 25 Statement stmt=con.createStatement();//创建一个Statement连接 26 int result=stmt.executeUpdate(sql);//执行sql语句 27 db.close(stmt,con); 28 return result; 29 } 30 public static void main(String[] args) throws Exception { 31 // TODO Auto-generated method stub 32 /*