搜索
您的当前位置:首页正文

java jdbc 连接mysql数据库 实现增删改查

2023-11-10 来源:哗拓教育

 

第四步,创建实体类(如上图,大家观察包的分配,我们将采用MVC思想设计本实例,有关于mvc的设计思想,请大家自行学习,这里不多说)代码如下:

 1 package com.czgo.model; 2 3 import java.io.Serializable; 4 5 /** 6 * 实体类:女神类 7 * 8 * @author AlanLee 9 * 10 */11 public class Goddess implements Serializable12 {13 private static final long serialVersionUID = 1L;14 15 /**16 * 唯一主键17 */18 private Integer id;19 /**20 * 姓名21 */22 private String name;23 /**24 * 手机号码25 */26 private String mobie;27 /**28 * 电子邮件29 */30 private String email;31 /**32 * 家庭住址33 */34 private String address;35 36 public Integer getId()37 {38 return id;39 }40 41 public void setId(Integer id)42 {43 this.id = id;44 }45 46 public String getName()47 {48 return name;49 }50 51 public void setName(String name)52 {53 this.name = name;54 }55 56 public String getMobie()57 {58 return mobie;59 }60 61 public void setMobie(String mobie)62 {63 this.mobie = mobie;64 }65 66 public String getEmail()67 {68 return email;69 }70 71 public void setEmail(String email)72 {73 this.email = email;74 }75 76 public String getAddress()77 {78 return address;79 }80 81 public void setAddress(String address)82 {83 this.address = address;84 }85 }

第五步,dao层的实现(这里由于是小例子没有写dao接口,实际工作中大型项目应该是要写dao接口的,便于程序的维护和扩展),代码如下:

 1 package com.czgo.dao; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.util.ArrayList; 8 import java.util.List; 9 10 import com.czgo.db.DBUtil; 11 import com.czgo.model.Goddess; 12 13 /** 14 * 数据层处理类 15 * 16 * @author AlanLee 17 * 18 */ 19 public class GoddessDao 20 { 21 /** 22 * 查询全部女神 23 * 24 * @return 25 * @throws SQLException 26 */ 27 public List<Goddess> query() throws SQLException 28 { 29 List<Goddess> goddessList = new ArrayList<Goddess>(); 30 31 // 获得数据库连接 32 Connection conn = DBUtil.getConnection(); 33 34 StringBuilder sb = new StringBuilder(); 35 sb.append("select id,name,mobie,email,address from goddess"); 36 37 // 通过数据库的连接操作数据库,实现增删改查 38 PreparedStatement ptmt = conn.prepareStatement(sb.toString()); 39 40 ResultSet rs = ptmt.executeQuery(); 41 42 Goddess goddess = null; 43 44 while (rs.next()) 45 { 46 goddess = new Goddess(); 47 goddess.setId(rs.getInt("id")); 48 goddess.setName(rs.getString("name")); 49 goddess.setMobie(rs.getString("mobie")); 50 goddess.setEmail(rs.getString("email")); 51 goddess.setAddress(rs.getString("address")); 52 53 goddessList.add(goddess); 54 } 55 return goddessList; 56 } 57 58 /** 59 * 查询单个女神 60 * 61 * @return 62 * @throws SQLException 63 */ 64 public Goddess queryById(Integer id) throws SQLException 65 { 66 Goddess g = null; 67 68 Connection conn = DBUtil.getConnection(); 69 70 String sql = "" + " select * from imooc_goddess " + " where id=? "; 71 72 PreparedStatement ptmt = conn.prepareStatement(sql); 73 74 ptmt.setInt(1, id); 75 76 ResultSet rs = ptmt.executeQuery(); 77 78 while (rs.next()) 79 { 80 g = new Goddess(); 81 g.setId(rs.getInt("id")); 82 g.setName(rs.getString("name")); 83 g.setMobie(rs.getString("mobie")); 84 g.setEmail(rs.getString("email")); 85 g.setAddress(rs.getString("address")); 86 } 87 88 return g; 89 } 90 91 /** 92 * 添加女神 93 * 94 * @throws SQLException 95 */ 96 public void addGoddess(Goddess goddess) throws SQLException 97 { 98 // 获得数据库连接 99 Connection conn = DBUtil.getConnection();100 101 String sql = "insert into goddess(name,mobie,email,address) values(?,?,?,?)";102 103 PreparedStatement ptmt = conn.prepareStatement(sql);104 105 ptmt.setString(1, goddess.getName());106 ptmt.setString(2, goddess.getMobie());107 ptmt.setString(3, goddess.getEmail());108 ptmt.setString(4, goddess.getAddress());109 110 ptmt.execute();111 }112 113 /**114 * 修改女神资料115 * 116 * @throws SQLException117 */118 public void updateGoddess(Goddess goddess) throws SQLException119 {120 Connection conn = DBUtil.getConnection();121 122 String sql = "update goddess set name=?,mobie=?,email=?,address=? where id=?";123 124 PreparedStatement ptmt = conn.prepareStatement(sql);125 126 ptmt.setString(1, goddess.getName());127 ptmt.setString(2, goddess.getMobie());128 ptmt.setString(3, goddess.getEmail());129 ptmt.setString(4, goddess.getAddress());130 131 ptmt.execute();132 }133 134 /**135 * 删除女神136 * 137 * @throws SQLException138 */139 public void deleteGoddess(Integer id) throws SQLException140 {141 Connection conn = DBUtil.getConnection();142 143 String sql = "delete from goddess where id=?";144 145 PreparedStatement ptmt = conn.prepareStatement(sql);146 147 ptmt.setInt(1, id);148 149 ptmt.execute();150 }151 }

第六步,控制层的实现(控制层在此处用来模仿控制层和界面,直接在这里构建数据,如果是界面的数据则通过请求传递接收参数即可,控制层的代码大家可以根据实际情况去更改完善,这里只是给大家抛砖引玉,做个简单的测试,时间比较紧,希望大家理解),代码如下:

 1 package com.czgo.action; 2 3 import java.sql.SQLException; 4 import java.util.List; 5 6 import com.czgo.dao.GoddessDao; 7 import com.czgo.model.Goddess; 8 9 /**10 * 控制层,直接在这里构建数据,界面的数据则通过请求传递接收即可,亦是同理11 * 12 * @author AlanLee13 * 14 */15 public class GoddessAction16 {17 /**18 * 新增女神19 * 20 * @param goddess21 * @throws Exception22 */23 public void add(Goddess goddess) throws Exception24 {25 GoddessDao dao = new GoddessDao();26 goddess.setName("苍井空");27 goddess.setMobie("52220000");28 goddess.setEmail("52220000@qq.com");29 goddess.setAddress("北京红灯区");30 dao.addGoddess(goddess);31 }32 33 /**34 * 查询单个女神35 * 36 * @param id37 * @return38 * @throws SQLException39 */40 public Goddess get(Integer id) throws SQLException41 {42 GoddessDao dao = new GoddessDao();43 return dao.queryById(id);44 }45 46 /**47 * 修改女神48 * 49 * @param goddess50 * @throws Exception51 */52 public void edit(Goddess goddess) throws Exception53 {54 GoddessDao dao = new GoddessDao();55 dao.updateGoddess(goddess);56 }57 58 /**59 * 删除女神60 * 61 * @param id62 * @throws SQLException63 */64 public void del(Integer id) throws SQLException65 {66 GoddessDao dao = new GoddessDao();67 dao.deleteGoddess(id);68 }69 70 /**71 * 查询全部女神72 * 73 * @return74 * @throws Exception75 */76 public List<Goddess> query() throws Exception77 {78 GoddessDao dao = new GoddessDao();79 return dao.query();80 }81 82 /**83 * 测试是否成功84 * 85 * @param args86 * @throws SQLException87 */88 public static void main(String[] args) throws SQLException89 {90 GoddessDao goddessDao = new GoddessDao();91 92 List<Goddess> goddessList = goddessDao.query();93 94 for (Goddess goddess : goddessList)95 {96 System.out.println(goddess.getName() + "," + goddess.getMobie() + "," + goddess.getEmail());97 }98 }99 }

最后,让我们看一下main方法的运行结果是否成功:

技术分享

这样,一个简单的java jdbc 连接mysql数据库 实现增删改查便完成了,大家可以在查询的基础上试着去做一个高级查询,也就是多条件查询来巩固jdbc的使用。

现在21:00,还没有吃晚饭,时间比较紧,所以没有给大家一一测试增删改查的功能,闲着没事做蛋疼的可以都去测试一下,如果发现问题,希望能够指正小Alan,小Alan有空的时候便去修正博文中的一些错误。

最后的最后,祝大家今晚都能够做一个美美的梦,小Alan吃晚饭去了,下次再会!

 

java jdbc 连接mysql数据库 实现增删改查

标签:

小编还为您整理了以下内容,可能对您也有帮助:

用java连接mysql实现对表中的数据查找,插入,修改等功能,

JDBC操作MySQL数据库的步骤

1、准备MySQL数据库驱动包:mysql-connector-java-5.0.8-bin.jar,一个项目中只能存在一个版本的驱动包

a、复制该驱动包,粘贴到项目中

b、选中项目里的驱动包,右键->Build Path->Add to Build Path

2、在类里写代码加载驱:决定连接哪种数据库

a、Class.forName("com.mysql.jdbc.Driver");

b、必须进行异常处理:ClassNotFoundException

3、连接数据库

a、Connection con=DriverManager.getConnection("连接字符串", "用户名", "密码");

b、连接字符串格式固定,不同数据库,格式不同:jdbc:mysql://要连接的计算机名称:端口号/要连接的数据库名称

c、必须进行异常处理:SQLException

4、拼写要执行的sql语句,必须是可以在数据库中执行的

5、创建执行sql语句的对象

a、Statement stmt=con.createStatement();

b、注意:Statement必须来自于java.sql包中

6、执行sql语句

a、执行insert、update和delete语句:int row=stmt.executeUpdate(sql);返回影响行数

b、执行查询语句:ResultSet rs=stmt.executeQuery(sql);返回查询结果

c、执行任意sql语句(DDL、DCL、DML和DQL等)

7、对执行结果进行处理

a、执行更新语句:判断影响行数是否为0,0表示失败,非0表示成功

b、对查询结果进行处理:

1) 结果集需要先移动、后取值 :rs.next();int id=rs.getInt(1);

String name=rs.getString("loginName");

2) 结果集有多条时,需要循环操作:

while(rs.next()){ System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getString(4)+"\t"+rs.getInt(5));

}

3) 不确定是否有查询结果时:if(rs.next()){说明有查询结果}else{没有查询结果}

4) 使用了聚合函数,一定有查询结果,查询结果是一行一列:

rs.next();

int result=rs.getInt(1);

注意:结果集取值时取出的时查询语句中包含的字段,与表中字段无关

9、关闭相关对象(先关闭结果集对象、在关闭执行语句对象,最后关闭连接对象)

例如:执行查询语句

Scanner input=new Scanner(System.in);

System.out.print("请输入登录名: ");

String name=input.next();

System.out.print("请输入密码: ");

String pass=input.next();

try {

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/userdb", "root", "root");

String sql="select COUNT(*) from UserInfo where loginName='"+name+"' and loginPass='"+pass+"'";

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery(sql);

rs.next();

int result=rs.getInt(1);

if(result!=0){

System.out.println("登录成功!");

}else{

System.out.println("用户名或密码错误,请重新登录!");

}

rs.close();

stmt.close();

con.close();

} catch (ClassNotFoundException e) {

System.out.println("加载驱动错误:"+e.getMessage());

} catch (SQLException e) {

System.out.println("数据库操作错误:"+e.getMessage());

}

执行添加、修改和删除语句

try {

//加载驱动

Class.forName("com.mysql.jdbc.Driver");

//连接数据库

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/userdb", "root", "root");

//拼写要执行的sql语句

String sql="update UserInfo set loginPass='111' where loginName='a'";

//String sql="insert UserInfo values(default,'test','test')";

//String sql="delete from UserInfo where loginName='a'";

//创建执行语句对象

Statement stmt=con.createStatement();

//执行

int row=stmt.executeUpdate(sql);

//处理结果

if(row==0){

System.out.println("修改失败!");

}else{

System.out.println("修改成功!");

}

//关闭

stmt.close();

con.close();

} catch (ClassNotFoundException e) {

System.out.println("驱动加载错误:"+e.getMessage());

} catch (SQLException e) {

System.out.println("数据库操作错误:"+e.getMessage());

}

Java连接MySql数据库,并且实现插入、删除、更新、选择操作

mysql建立一个名为“vge_whu”的数据库,并在该数据库中新建一个user表。具体信息如下图所示。

技术分享

MySQLHelper.java,mySQL操作类,后面陆续完善该类,源码如下:

 

[java] view plain copy print?技术分享技术分享
  1. package edu.whu.vge;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.PreparedStatement;  
  6. import java.sql.SQLException;  
  7.   
  8. /** 
  9.  *  
  10.  * 项目名称:JavaSQL1    
  11.  * 类名称:DBHelper    
  12.  * 类描述:MySQL数据库操作类    
  13.  * 创建人:Administrator 
  14.  * 创建时间:2014-11-25 下午5:11:11    
  15.  * 修改备注:    
  16.  * @version 
  17.  */  
  18. public class MySQLHelper  
  19. {  
  20.     public static final String url = "jdbc:mysql://127.0.0.1/vge_whu"; //数据库连接  
  21.     public static final String name = "com.mysql.jdbc.Driver";   //程序驱动  
  22.     public static final String user = "root";  //用户名  
  23.     public static final String password = "abc@123"; //密码  
  24.   
  25.     public Connection conn = null;  
  26.     public PreparedStatement pst = null;  
  27.   
  28.     /** 
  29.      *  
  30.      * 创建一个新的实例 DBHelper.    
  31.      *    
  32.      * @param sql: SQL查询语句 
  33.      */  
  34.     public MySQLHelper(String sql)  
  35.     {  
  36.         try  
  37.         {  
  38.             Class.forName(name);// 指定连接类型  
  39.             conn = DriverManager.getConnection(url, user, password);// 获取连接  
  40.             pst = conn.prepareStatement(sql);// 准备执行语句  
  41.         } catch (Exception e)  
  42.         {  
  43.             e.printStackTrace();  
  44.         }  
  45.     }  
  46.   
  47.     /** 
  48.      *  
  49.      * 方法名称: close ; 
  50.      * 方法描述:  关闭数据库连接 ; 
  51.      * 参数 :  
  52.      * 返回类型: void ; 
  53.      * 创建人:James; 
  54.      * 创建时间:2014-11-25 下午7:00:12; 
  55.      * @throws 
  56.      */  
  57.     public void close()  
  58.     {  
  59.         try  
  60.         {  
  61.             this.conn.close();  
  62.             this.pst.close();  
  63.         } catch (SQLException e)  
  64.         {  
  65.             e.printStackTrace();  
  66.         }  
  67.     }  
  68.   
  69. }  

再写一个java文件来调用MySQLHelper类执行相关操作,暂时只有查询,后面补充新增、删除、更新等操作。

 

[java] view plain copy print?技术分享技术分享
  1. package edu.whu.vge;  
  2.   
  3. import java.sql.*;  
  4.   
  5. /** 
  6.  *  
  7.  * 项目名称:JavaSQL1  
  8.  * 类名称:JDBCTest  
  9.  * 类描述: Java连接MySQL 
  10.  * 测试 创建人:Administrator 
  11.  * 创建时间:2014-11-25 下午5:11:43 
  12.  *  修改备注: 
  13.  *  
  14.  * @version 1.0 
  15.  */  
  16. public class JDBCTest  
  17. {  
  18.     static String sql = null;  
  19.     static MySQLHelper db1 = null;  
  20.     static ResultSet ret = null;  
  21.   
  22.     public static void main(String[] args)  
  23.     {  
  24.         sql = "select * from user";// SQL语句  
  25.         db1 = new MySQLHelper(sql);// 创建DBHelper对象  
  26.         System.out.println("编号--姓名--性别--年龄-------电话-------QQ---------邮箱");  
  27.         try  
  28.         {  
  29.             ret = db1.pst.executeQuery();// 执行语句,得到结果集  
  30.             while (ret.next())  
  31.             {  
  32.                 String uId = ret.getString(1);  
  33.                 String uName = ret.getString(2);  
  34.                 String uSex = ret.getString(3);  
  35.                 String uAge = ret.getString(4);  
  36.                 String uTel = ret.getString(5);  
  37.                 String uQQ = ret.getString(6);  
  38.                 String uMail = ret.getString(7);  
  39.                 System.out.println(uId + "" + uName + "" + uSex + ""  
  40.                         + uAge + "" + uTel + "" + uQQ + "" + uMail);  
  41.             }// 显示数据  
  42.             ret.close();  
  43.             db1.close();// 关闭连接  
  44.         } catch (SQLException e)  
  45.         {  
  46.             e.printStackTrace();  
  47.         }  
  48.     }  
  49.   
  50. }  

执行结果如下图所示。

技术分享

-----------------------------华丽的分割线(2014.11.26)--------------------------------------

MySQLHelper操作类

 

[java] view plain copy print?技术分享技术分享
  1. package edu.whu.vge;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.PreparedStatement;  
  6. import java.sql.ResultSet;  
  7. import java.sql.SQLException;  
  8.   
  9. /** 
  10.  *  
  11.  * @项目名称:JavaSQL1 
  12.  * @类名称:MySQLHelper 
  13.  * @类描述:mysql操作类 
  14.  * @创建人:奔跑的鸡丝 
  15.  * @创建时间:2014-11-25 下午8:58:34 
  16.  * @修改备注: 
  17.  * @版本: 
  18.  */  
  19. public class MySQLHelper  
  20. {  
  21.     public static final String url = "jdbc:mysql://127.0.0.1/vge_whu"; // 数据库连接  
  22.     public static final String name = "com.mysql.jdbc.Driver"; // 程序驱动  
  23.     public static final String user = "root"; // 用户名  
  24.     public static final String password = "abc@123"; // 密码  
  25.   
  26.     public Connection connection = null; // 数据库连接  
  27.     public PreparedStatement preparedStatement = null; // 待查询语句描述对象  
  28.   
  29.     /** 
  30.      *  
  31.      * 创建一个新的实例 DBHelper. 
  32.      *  
  33.      * @param sql 
  34.      *            : SQL查询语句 
  35.      */  
  36.     public MySQLHelper()  
  37.     {  
  38.         try  
  39.         {  
  40.             Class.forName(name);// 指定连接类型  
  41.             connection = DriverManager.getConnection(url, user, password);// 获取连接  
  42.         } catch (Exception e)  
  43.         {  
  44.             e.printStackTrace();  
  45.         }  
  46.     }  
  47.   
  48.     /** 
  49.      *  
  50.      * @方法名称: close ; 
  51.      * @方法描述: 关闭数据库 ; 
  52.      * @参数 : 
  53.      * @返回类型: void ; 
  54.      * @创建人:奔跑的鸡丝 ; 
  55.      * @创建时间:2014-11-25 下午8:58:14; 
  56.      * @throws 
  57.      */  
  58.     public void close()  
  59.     {  
  60.         try  
  61.         {  
  62.             this.connection.close();  
  63.             this.preparedStatement.close();  
  64.         } catch (SQLException e)  
  65.         {  
  66.             System.out.println("关闭数据库出现问题!!");  
  67.             e.printStackTrace();  
  68.         }  
  69.     }  
  70.   
  71.     /** 
  72.      *  
  73.      * @方法名称: query ; 
  74.      * @方法描述: 查询操作 ; 
  75.      * @参数 :@param sql:查询操作语句 ; 
  76.      * @返回类型: ResultSet :查询结果数据集; 
  77.      * @创建人:奔跑的鸡丝 ; 
  78.      * @创建时间:2014-11-25 下午8:49:25; 
  79.      * @throws 
  80.      */  
  81.     public ResultSet query(String sql)  
  82.     {  
  83.         ResultSet resultSet = null;  
  84.   
  85.         try  
  86.         {  
  87.             preparedStatement = connection.prepareStatement(sql); // 准备执行语句  
  88.             resultSet = preparedStatement.executeQuery();  
  89.   
  90.         } catch (Exception e)  
  91.         {  
  92.             System.out.println("查询错误,请检查!!");  
  93.             e.printStackTrace();  
  94.         }  
  95.         return resultSet;  
  96.     }  
  97.   
  98.     /** 
  99.      *  
  100.      * @方法名称: executeNonquery ; 
  101.      * @方法描述: 插入、修改、删除等操作 ; 
  102.      * @参数 :@param sql:插入语句 
  103.      * @返回类型: boolean ; 
  104.      * @创建人:奔跑的鸡丝; 
  105.      * @创建时间:2014-11-25 下午8:45:49; 
  106.      * @throws 
  107.      */  
  108.     public boolean executeNonquery(String sql)  
  109.     {  
  110.         boolean flag = false;  
  111.         try  
  112.         {  
  113.             preparedStatement = connection.prepareStatement(sql);  
  114.             preparedStatement.executeUpdate();  
  115.             flag = true;  
  116.   
  117.         } catch (Exception e)  
  118.         {  
  119.             System.out.println("插入数据库时出现错误!!");  
  120.             e.printStackTrace();  
  121.         }  
  122.         return flag;  
  123.     }  
  124.   
  125.     /** 
  126.      *  
  127.      * @方法名称: getCount ; 
  128.      * @方法描述:  获取表记录数 ; 
  129.      * @参数 :@param sql 
  130.      * @参数 :@return  
  131.      * @返回类型: int 记录数; 
  132.      * @创建人:奔跑的鸡丝 ; 
  133.      * @创建时间:2014-11-26 下午2:40:37; 
  134.      * @throws 
  135.      */  
  136.     public int getCount(String sql)  
  137.     {  
  138.         int count=0;  
  139.         try  
  140.         {  
  141.             preparedStatement=connection.prepareStatement(sql);  
  142.             ResultSet resultSet=preparedStatement.executeQuery();  
  143.             resultSet.last();  
  144.             count=resultSet.getRow();  
  145.             resultSet.close();  
  146.               
  147.         } catch (Exception e)  
  148.         {  
  149.             System.out.println("查询总记录数失败!!");  
  150.             e.printStackTrace();  
  151.         }  
  152.         return count;  
  153.     }  
  154. }  


实例调用:

 

[java] view plain copy print?技术分享技术分享
    1. package edu.whu.vge;  
    2.   
    3. import java.sql.*;  
    4.   
    5. /** 
    6.  *  
    7.  * 项目名称:JavaSQL1 类名称:JDBCTest 类描述: Java连接MySQL 测试 创建人:Administrator 
    8.  * 创建时间:2014-11-25 下午5:11:43 修改备注: 
    9.  *  
    10.  * @version 1.0 
    11.  */  
    12. public class JDBCTest  
    13. {  
    14.   
    15.     static MySQLHelper pMySQLHelper = null;  
    16.   
    17.     public static void main(String[] args)  
    18.     {  
    19.           
    20.         insert();  
    21.         update();  
    22.         delete();  
    23.         query();  
    24.         getCount();  
    25.     }  
    26.   
    27.     /** 
    28.      *  
    29.      * @方法名称: query ; 
    30.      * @方法描述: 查询数据库 ; 
    31.      * @参数 : 
    32.      * @返回类型: void ; 
    33.      * @创建人:奔跑的鸡丝 ; 
    34.      * @创建时间:2014-11-25 下午9:03:00; 
    35.      * @throws 
    36.      */  
    37.     private static void query()  
    38.     {  
    39.         pMySQLHelper = new MySQLHelper();// 创建MySQLHelper对象  
    40.         String sql = "select * from user"; // 查询SQL语句  
    41.         ResultSet pResultSet = null;  
    42.         System.out.println("编号--姓名--性别--年龄-------电话-------QQ---------邮箱");  
    43.         try  
    44.         {  
    45.             pResultSet = pMySQLHelper.query(sql);// 执行语句,得到结果集  
    46.   
    47.             // 显示数据  
    48.             while (pResultSet.next())  
    49.             {  
    50.                 String uId = pResultSet.getString(1);  
    51.                 String uName = pResultSet.getString(2);  
    52.                 String uSex = pResultSet.getString(3);  
    53.                 String uAge = pResultSet.getString(4);  
    54.                 String uTel = pResultSet.getString(5);  
    55.                 String uQQ = pResultSet.getString(6);  
    56.                 String uMail = pResultSet.getString(7);  
    57.                 System.out.println(uId + "" + uName + "" + uSex + ""  
    58.                         + uAge + "" + uTel + "" + uQQ + "" + uMail);  
    59.             }  
    60.             pMySQLHelper.close();  
    61.             pResultSet.close();  
    62.   
    63.         } catch (SQLException e)  
    64.         {  
    65.             e.printStackTrace();  
    66.         }  
    67.     }  
    68.   
    69.     /** 
    70.      *  
    71.      * @方法名称: insert ; 
    72.      * @方法描述: 插入 ; 
    73.      * @参数 : 
    74.      * @返回类型: void ; 
    75.      * @创建人:奔跑的鸡丝 ; 
    76.      * @创建时间:2014-11-25 下午9:40:41; 
    77.      * @throws 
    78.      */  
    79.     private static void insert()  
    80.     {  
    81.         try  
    82.         {  
    83.             pMySQLHelper = new MySQLHelper();  
    84.             String insert = "Insert Into user Values (‘2010301610308‘,‘老大‘,‘男‘,58,‘123456789‘,‘123456789‘,‘1234@163.com‘)";  
    85.             if (pMySQLHelper.executeNonquery(insert))  
    86.             {  
    87.                 System.out.println("插入成功!!");  
    88.             }  
    89.             pMySQLHelper.close();  
    90.         } catch (Exception e)  
    91.         {  
    92.             System.out.println("插入出錯!!");  
    93.             e.printStackTrace();  
    94.         }  
    95.   
    96.     }  
    97.   
    98.     /** 
    99.      *  
    100.      * @方法名称: update ; 
    101.      * @方法描述: 修改 ; 
    102.      * @参数 : 
    103.      * @返回类型: void ; 
    104.      * @创建人:奔跑的鸡丝 ; 
    105.      * @创建时间:2014-11-26 下午2:19:14; 
    106.      * @throws 
    107.      */  
    108.     private static void update()  
    109.     {  
    110.         pMySQLHelper = new MySQLHelper();  
    111.         String update = "Update user Set Name=‘奔跑的鸡丝‘ Where StudentID=‘2010301610305‘";  
    112.         if (pMySQLHelper.executeNonquery(update))  
    113.         {  
    114.             System.out.println("修改成功!!");  
    115.   
    116.         }  
    117.         pMySQLHelper.close();  
    118.     }  
    119.   
    120.     /** 
    121.      *  
    122.      * @方法名称: delete ; 
    123.      * @方法描述: 删除 ; 
    124.      * @参数 : 
    125.      * @返回类型: void ; 
    126.      * @创建人:奔跑的鸡丝 ; 
    127.      * @创建时间:2014-11-26 下午2:33:40; 
    128.      * @throws 
    129.      */  
    130.     private static void delete()  
    131.     {  
    132.         pMySQLHelper = new MySQLHelper();  
    133.         String delete = "Delete From user Where Name=‘朱庆‘";  
    134.         if (pMySQLHelper.executeNonquery(delete))  
    135.         {  
    136.             System.out.println("删除成功!!");  
    137.   
    138.         }  
    139.         pMySQLHelper.close();  
    140.     }  
    141.   
    142.     private static void getCount()  
    143.     {  
    144.         pMySQLHelper=new MySQLHelper();  
    145.         String getCountString="Select * From user";  
    146.         System.out.println("记录数为:"+pMySQLHelper.getCount(getCountString));  
    147.           
    148.     }  
    149. from: http://blog.csdn.net/giser_whu/article/details/41487213

java操作MySQL数据库(插入、删除、修改、查询、获取所有行数)

标签:

Java连接MySql数据库,并且实现插入、删除、更新、选择操作

mysql建立一个名为“vge_whu”的数据库,并在该数据库中新建一个user表。具体信息如下图所示。

技术分享

MySQLHelper.java,mySQL操作类,后面陆续完善该类,源码如下:

 

[java] view plain copy print?技术分享技术分享
  1. package edu.whu.vge;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.PreparedStatement;  
  6. import java.sql.SQLException;  
  7.   
  8. /** 
  9.  *  
  10.  * 项目名称:JavaSQL1    
  11.  * 类名称:DBHelper    
  12.  * 类描述:MySQL数据库操作类    
  13.  * 创建人:Administrator 
  14.  * 创建时间:2014-11-25 下午5:11:11    
  15.  * 修改备注:    
  16.  * @version 
  17.  */  
  18. public class MySQLHelper  
  19. {  
  20.     public static final String url = "jdbc:mysql://127.0.0.1/vge_whu"; //数据库连接  
  21.     public static final String name = "com.mysql.jdbc.Driver";   //程序驱动  
  22.     public static final String user = "root";  //用户名  
  23.     public static final String password = "abc@123"; //密码  
  24.   
  25.     public Connection conn = null;  
  26.     public PreparedStatement pst = null;  
  27.   
  28.     /** 
  29.      *  
  30.      * 创建一个新的实例 DBHelper.    
  31.      *    
  32.      * @param sql: SQL查询语句 
  33.      */  
  34.     public MySQLHelper(String sql)  
  35.     {  
  36.         try  
  37.         {  
  38.             Class.forName(name);// 指定连接类型  
  39.             conn = DriverManager.getConnection(url, user, password);// 获取连接  
  40.             pst = conn.prepareStatement(sql);// 准备执行语句  
  41.         } catch (Exception e)  
  42.         {  
  43.             e.printStackTrace();  
  44.         }  
  45.     }  
  46.   
  47.     /** 
  48.      *  
  49.      * 方法名称: close ; 
  50.      * 方法描述:  关闭数据库连接 ; 
  51.      * 参数 :  
  52.      * 返回类型: void ; 
  53.      * 创建人:James; 
  54.      * 创建时间:2014-11-25 下午7:00:12; 
  55.      * @throws 
  56.      */  
  57.     public void close()  
  58.     {  
  59.         try  
  60.         {  
  61.             this.conn.close();  
  62.             this.pst.close();  
  63.         } catch (SQLException e)  
  64.         {  
  65.             e.printStackTrace();  
  66.         }  
  67.     }  
  68.   
  69. }  

再写一个java文件来调用MySQLHelper类执行相关操作,暂时只有查询,后面补充新增、删除、更新等操作。

 

[java] view plain copy print?技术分享技术分享
  1. package edu.whu.vge;  
  2.   
  3. import java.sql.*;  
  4.   
  5. /** 
  6.  *  
  7.  * 项目名称:JavaSQL1  
  8.  * 类名称:JDBCTest  
  9.  * 类描述: Java连接MySQL 
  10.  * 测试 创建人:Administrator 
  11.  * 创建时间:2014-11-25 下午5:11:43 
  12.  *  修改备注: 
  13.  *  
  14.  * @version 1.0 
  15.  */  
  16. public class JDBCTest  
  17. {  
  18.     static String sql = null;  
  19.     static MySQLHelper db1 = null;  
  20.     static ResultSet ret = null;  
  21.   
  22.     public static void main(String[] args)  
  23.     {  
  24.         sql = "select * from user";// SQL语句  
  25.         db1 = new MySQLHelper(sql);// 创建DBHelper对象  
  26.         System.out.println("编号--姓名--性别--年龄-------电话-------QQ---------邮箱");  
  27.         try  
  28.         {  
  29.             ret = db1.pst.executeQuery();// 执行语句,得到结果集  
  30.             while (ret.next())  
  31.             {  
  32.                 String uId = ret.getString(1);  
  33.                 String uName = ret.getString(2);  
  34.                 String uSex = ret.getString(3);  
  35.                 String uAge = ret.getString(4);  
  36.                 String uTel = ret.getString(5);  
  37.                 String uQQ = ret.getString(6);  
  38.                 String uMail = ret.getString(7);  
  39.                 System.out.println(uId + "" + uName + "" + uSex + ""  
  40.                         + uAge + "" + uTel + "" + uQQ + "" + uMail);  
  41.             }// 显示数据  
  42.             ret.close();  
  43.             db1.close();// 关闭连接  
  44.         } catch (SQLException e)  
  45.         {  
  46.             e.printStackTrace();  
  47.         }  
  48.     }  
  49.   
  50. }  

执行结果如下图所示。

技术分享

-----------------------------华丽的分割线(2014.11.26)--------------------------------------

MySQLHelper操作类

 

[java] view plain copy print?技术分享技术分享
  1. package edu.whu.vge;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.PreparedStatement;  
  6. import java.sql.ResultSet;  
  7. import java.sql.SQLException;  
  8.   
  9. /** 
  10.  *  
  11.  * @项目名称:JavaSQL1 
  12.  * @类名称:MySQLHelper 
  13.  * @类描述:mysql操作类 
  14.  * @创建人:奔跑的鸡丝 
  15.  * @创建时间:2014-11-25 下午8:58:34 
  16.  * @修改备注: 
  17.  * @版本: 
  18.  */  
  19. public class MySQLHelper  
  20. {  
  21.     public static final String url = "jdbc:mysql://127.0.0.1/vge_whu"; // 数据库连接  
  22.     public static final String name = "com.mysql.jdbc.Driver"; // 程序驱动  
  23.     public static final String user = "root"; // 用户名  
  24.     public static final String password = "abc@123"; // 密码  
  25.   
  26.     public Connection connection = null; // 数据库连接  
  27.     public PreparedStatement preparedStatement = null; // 待查询语句描述对象  
  28.   
  29.     /** 
  30.      *  
  31.      * 创建一个新的实例 DBHelper. 
  32.      *  
  33.      * @param sql 
  34.      *            : SQL查询语句 
  35.      */  
  36.     public MySQLHelper()  
  37.     {  
  38.         try  
  39.         {  
  40.             Class.forName(name);// 指定连接类型  
  41.             connection = DriverManager.getConnection(url, user, password);// 获取连接  
  42.         } catch (Exception e)  
  43.         {  
  44.             e.printStackTrace();  
  45.         }  
  46.     }  
  47.   
  48.     /** 
  49.      *  
  50.      * @方法名称: close ; 
  51.      * @方法描述: 关闭数据库 ; 
  52.      * @参数 : 
  53.      * @返回类型: void ; 
  54.      * @创建人:奔跑的鸡丝 ; 
  55.      * @创建时间:2014-11-25 下午8:58:14; 
  56.      * @throws 
  57.      */  
  58.     public void close()  
  59.     {  
  60.         try  
  61.         {  
  62.             this.connection.close();  
  63.             this.preparedStatement.close();  
  64.         } catch (SQLException e)  
  65.         {  
  66.             System.out.println("关闭数据库出现问题!!");  
  67.             e.printStackTrace();  
  68.         }  
  69.     }  
  70.   
  71.     /** 
  72.      *  
  73.      * @方法名称: query ; 
  74.      * @方法描述: 查询操作 ; 
  75.      * @参数 :@param sql:查询操作语句 ; 
  76.      * @返回类型: ResultSet :查询结果数据集; 
  77.      * @创建人:奔跑的鸡丝 ; 
  78.      * @创建时间:2014-11-25 下午8:49:25; 
  79.      * @throws 
  80.      */  
  81.     public ResultSet query(String sql)  
  82.     {  
  83.         ResultSet resultSet = null;  
  84.   
  85.         try  
  86.         {  
  87.             preparedStatement = connection.prepareStatement(sql); // 准备执行语句  
  88.             resultSet = preparedStatement.executeQuery();  
  89.   
  90.         } catch (Exception e)  
  91.         {  
  92.             System.out.println("查询错误,请检查!!");  
  93.             e.printStackTrace();  
  94.         }  
  95.         return resultSet;  
  96.     }  
  97.   
  98.     /** 
  99.      *  
  100.      * @方法名称: executeNonquery ; 
  101.      * @方法描述: 插入、修改、删除等操作 ; 
  102.      * @参数 :@param sql:插入语句 
  103.      * @返回类型: boolean ; 
  104.      * @创建人:奔跑的鸡丝; 
  105.      * @创建时间:2014-11-25 下午8:45:49; 
  106.      * @throws 
  107.      */  
  108.     public boolean executeNonquery(String sql)  
  109.     {  
  110.         boolean flag = false;  
  111.         try  
  112.         {  
  113.             preparedStatement = connection.prepareStatement(sql);  
  114.             preparedStatement.executeUpdate();  
  115.             flag = true;  
  116.   
  117.         } catch (Exception e)  
  118.         {  
  119.             System.out.println("插入数据库时出现错误!!");  
  120.             e.printStackTrace();  
  121.         }  
  122.         return flag;  
  123.     }  
  124.   
  125.     /** 
  126.      *  
  127.      * @方法名称: getCount ; 
  128.      * @方法描述:  获取表记录数 ; 
  129.      * @参数 :@param sql 
  130.      * @参数 :@return  
  131.      * @返回类型: int 记录数; 
  132.      * @创建人:奔跑的鸡丝 ; 
  133.      * @创建时间:2014-11-26 下午2:40:37; 
  134.      * @throws 
  135.      */  
  136.     public int getCount(String sql)  
  137.     {  
  138.         int count=0;  
  139.         try  
  140.         {  
  141.             preparedStatement=connection.prepareStatement(sql);  
  142.             ResultSet resultSet=preparedStatement.executeQuery();  
  143.             resultSet.last();  
  144.             count=resultSet.getRow();  
  145.             resultSet.close();  
  146.               
  147.         } catch (Exception e)  
  148.         {  
  149.             System.out.println("查询总记录数失败!!");  
  150.             e.printStackTrace();  
  151.         }  
  152.         return count;  
  153.     }  
  154. }  


实例调用:

 

[java] view plain copy print?技术分享技术分享
    1. package edu.whu.vge;  
    2.   
    3. import java.sql.*;  
    4.   
    5. /** 
    6.  *  
    7.  * 项目名称:JavaSQL1 类名称:JDBCTest 类描述: Java连接MySQL 测试 创建人:Administrator 
    8.  * 创建时间:2014-11-25 下午5:11:43 修改备注: 
    9.  *  
    10.  * @version 1.0 
    11.  */  
    12. public class JDBCTest  
    13. {  
    14.   
    15.     static MySQLHelper pMySQLHelper = null;  
    16.   
    17.     public static void main(String[] args)  
    18.     {  
    19.           
    20.         insert();  
    21.         update();  
    22.         delete();  
    23.         query();  
    24.         getCount();  
    25.     }  
    26.   
    27.     /** 
    28.      *  
    29.      * @方法名称: query ; 
    30.      * @方法描述: 查询数据库 ; 
    31.      * @参数 : 
    32.      * @返回类型: void ; 
    33.      * @创建人:奔跑的鸡丝 ; 
    34.      * @创建时间:2014-11-25 下午9:03:00; 
    35.      * @throws 
    36.      */  
    37.     private static void query()  
    38.     {  
    39.         pMySQLHelper = new MySQLHelper();// 创建MySQLHelper对象  
    40.         String sql = "select * from user"; // 查询SQL语句  
    41.         ResultSet pResultSet = null;  
    42.         System.out.println("编号--姓名--性别--年龄-------电话-------QQ---------邮箱");  
    43.         try  
    44.         {  
    45.             pResultSet = pMySQLHelper.query(sql);// 执行语句,得到结果集  
    46.   
    47.             // 显示数据  
    48.             while (pResultSet.next())  
    49.             {  
    50.                 String uId = pResultSet.getString(1);  
    51.                 String uName = pResultSet.getString(2);  
    52.                 String uSex = pResultSet.getString(3);  
    53.                 String uAge = pResultSet.getString(4);  
    54.                 String uTel = pResultSet.getString(5);  
    55.                 String uQQ = pResultSet.getString(6);  
    56.                 String uMail = pResultSet.getString(7);  
    57.                 System.out.println(uId + "" + uName + "" + uSex + ""  
    58.                         + uAge + "" + uTel + "" + uQQ + "" + uMail);  
    59.             }  
    60.             pMySQLHelper.close();  
    61.             pResultSet.close();  
    62.   
    63.         } catch (SQLException e)  
    64.         {  
    65.             e.printStackTrace();  
    66.         }  
    67.     }  
    68.   
    69.     /** 
    70.      *  
    71.      * @方法名称: insert ; 
    72.      * @方法描述: 插入 ; 
    73.      * @参数 : 
    74.      * @返回类型: void ; 
    75.      * @创建人:奔跑的鸡丝 ; 
    76.      * @创建时间:2014-11-25 下午9:40:41; 
    77.      * @throws 
    78.      */  
    79.     private static void insert()  
    80.     {  
    81.         try  
    82.         {  
    83.             pMySQLHelper = new MySQLHelper();  
    84.             String insert = "Insert Into user Values (‘2010301610308‘,‘老大‘,‘男‘,58,‘123456789‘,‘123456789‘,‘1234@163.com‘)";  
    85.             if (pMySQLHelper.executeNonquery(insert))  
    86.             {  
    87.                 System.out.println("插入成功!!");  
    88.             }  
    89.             pMySQLHelper.close();  
    90.         } catch (Exception e)  
    91.         {  
    92.             System.out.println("插入出錯!!");  
    93.             e.printStackTrace();  
    94.         }  
    95.   
    96.     }  
    97.   
    98.     /** 
    99.      *  
    100.      * @方法名称: update ; 
    101.      * @方法描述: 修改 ; 
    102.      * @参数 : 
    103.      * @返回类型: void ; 
    104.      * @创建人:奔跑的鸡丝 ; 
    105.      * @创建时间:2014-11-26 下午2:19:14; 
    106.      * @throws 
    107.      */  
    108.     private static void update()  
    109.     {  
    110.         pMySQLHelper = new MySQLHelper();  
    111.         String update = "Update user Set Name=‘奔跑的鸡丝‘ Where StudentID=‘2010301610305‘";  
    112.         if (pMySQLHelper.executeNonquery(update))  
    113.         {  
    114.             System.out.println("修改成功!!");  
    115.   
    116.         }  
    117.         pMySQLHelper.close();  
    118.     }  
    119.   
    120.     /** 
    121.      *  
    122.      * @方法名称: delete ; 
    123.      * @方法描述: 删除 ; 
    124.      * @参数 : 
    125.      * @返回类型: void ; 
    126.      * @创建人:奔跑的鸡丝 ; 
    127.      * @创建时间:2014-11-26 下午2:33:40; 
    128.      * @throws 
    129.      */  
    130.     private static void delete()  
    131.     {  
    132.         pMySQLHelper = new MySQLHelper();  
    133.         String delete = "Delete From user Where Name=‘朱庆‘";  
    134.         if (pMySQLHelper.executeNonquery(delete))  
    135.         {  
    136.             System.out.println("删除成功!!");  
    137.   
    138.         }  
    139.         pMySQLHelper.close();  
    140.     }  
    141.   
    142.     private static void getCount()  
    143.     {  
    144.         pMySQLHelper=new MySQLHelper();  
    145.         String getCountString="Select * From user";  
    146.         System.out.println("记录数为:"+pMySQLHelper.getCount(getCountString));  
    147.           
    148.     }  
    149. from: http://blog.csdn.net/giser_whu/article/details/41487213

java操作MySQL数据库(插入、删除、修改、查询、获取所有行数)

标签:

编写一个java程序,通过jdbc访问数据库实现对数据库的插入,删除,修改和查询操作

我刚写了一个只有插入的,望采纳

import java.sql.*;

import java.util.*;

public class TestPre {

public static void main(String[] args) {

int i=0,deptno=0;//i只做while循环使用,deptno是表dept2中的一个属性,类型是int

String dname=null,loc=null;//dname和loc也是表dept2的属性,类型是String

Scanner s=new Scanner(System.in);

System.out.println("请输入3个参数");

while(i<3){

try{

deptno=s.nextInt();

i++;

dname=s.next();

i++;

loc=s.next();

i++;

}catch(InputMismatchException e){

System.out.println("输入的类型不符,退出");

System.exit(-1);

}

}

Connection conn=null;

PreparedStatement pstmt=null;

try {

Class.forName("com.mysql.jdbc.Driver");

conn = DriverManager.getConnection("jdbc:mysql://localhost/mydata?"+ "user=root&password=root");

pstmt=conn.prepareStatement("insert into dept2 values(?,?,?)");

pstmt.setInt(1, deptno);

pstmt.setString(2, dname);

pstmt.setString(3, loc);

pstmt.executeUpdate();

System.out.println("插入完成");

} catch (ClassNotFoundException e) {

System.out.println("连接数据库不成功,程序退出");

System.exit(-1);

} catch (SQLException e) {

System.out.println("连接数据库不成功,程序退出");

System.exit(-1);

}

finally{

try{

if(pstmt!=null){

pstmt.close();

pstmt=null;

}

if(conn!=null){

conn.close();

conn=null;

}

}catch(SQLException e){

e.printStackTrace();

}

}

}

}

请问如何对用Java对mysql进行增删改查等方法?

package com.ly520.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

/**
* mysql数据库操作类。
*
* @author Ryoma
*
*/
public class MySqlOperate implements SqlOperate {

private Connection con;
private String DBname;
private String sql;

/**
* Mysql数据库初始化包名
*/
private String INIT_SQL_CTX = "org.gjt.mm.mysql.Driver";
/**
* MYSQL数据库服务参数:服务器IP地址和端口
*/
private String SQL_SERVICE = "jdbc:mysql://127.0.0.1:3306?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&mysqlEncoding=utf8";
/**
* MYSQL数据库参数:系统管理用户
*/
private String SQL_SYSTEM_USER = "root";
/**
* MYSQL数据库参数:系统管理密码
*/
private String SQL_SYSTEM_PASSWORD = "123456";

/**
* 初始化链接方法。此方法不需要再使用use Dbname;
*/
public MySqlOperate() {
try {
Context ctx = new InitialContext();
if (ctx == null)
throw new Exception("Boom - No Context");
// java:comp/env/jdbc/imabled_mysql 为配置的连接池的jndi名称。
DataSource ds = (DataSource) ctx
.lookup("java:comp/env/jdbc/imabled_mysql");
con = ds.getConnection();
} catch (Exception ex) {
ex.printStackTrace();
}
}

/**
* 指定库名的连接方法,此方法没有使用连接池,不赞成使用。
*
* @param DBn
*/
public MySqlOperate(String DBn) {
try {
Class.forName(this.INIT_SQL_CTX);

} catch (java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
try {
con = DriverManager.getConnection(this.SQL_SERVICE + "/" + DBn,
this.SQL_SYSTEM_USER, this.SQL_SYSTEM_PASSWORD);
DBname = DBn;
} catch (SQLException ex) {
ex.printStackTrace();
}
}

public boolean add(String tablename, Hashtable searchdetail) {
Statement stmt = null;
Enumeration key_values = searchdetail.keys();
String key, value;
String temp = (String) key_values.nextElement();
key = temp;
value = "'" + searchdetail.get(temp) + "'";
while (key_values.hasMoreElements()) {
temp = (String) key_values.nextElement();
key = key + "," + temp;
value = value + "," + "'" + searchdetail.get(temp) + "'";
}
try {
useDB();
stmt = con.createStatement();
sql = "insert into " + tablename + " (" + key + ") " + " VALUES ("
+ value + ")";
stmt.executeUpdate(sql);
return true;

} catch (SQLException ex) {
System.out.println("执行的出错的sql语句:" + sql);
ex.printStackTrace();
return false;
} finally {
closeStmt(stmt);
}
}

public boolean batchImport(String tablename, List list, String[] fields)
throws SQLException {
PreparedStatement ps = null;
String key, value;
key = toString(fields);
String[] values = new String[fields.length];
for (int i = 0; i < values.length; i++) {
values[i] = "?";
}
value = toString(values);
try {
useDB();
con.setAutoCommit(false);
System.out.println("insert into " + tablename + " (" + key + ") "
+ " VALUES (" + value + ")");
ps = con.prepareStatement("insert into " + tablename + " (" + key
+ ") " + " VALUES (" + value + ")");
String[] tmpData = null;
for (int i = 0; i < list.size(); i++) {
tmpData = (String[]) list.get(i);
for (int j = 0; j < fields.length && j < tmpData.length; j++) {
ps.setString(j + 1, tmpData[j]);
}
ps.addBatch();// 添加执行的语句。
}
int[] count = ps.executeBatch();// 批量执行
con.commit();
return true;
} catch (SQLException ex) {
throw ex;
} finally {
try {
if (ps != null) {
ps.clearParameters();
ps.close();
ps = null;
}
} catch (SQLException e) {
throw e;
}
}
}

public boolean delete(String tablename, String filter) {
Statement stmt = null;
String value;
try {
useDB();
stmt = con.createStatement();
sql = "delete from " + tablename + " where " + filter;
stmt.executeUpdate(sql);
return true;
} catch (SQLException e) {
System.out.println("执行的出错的sql语句:" + sql);
e.printStackTrace();
return false;
} finally {
closeStmt(stmt);
}
}

public Hashtable list(String sql) {
Hashtable[] infoList = search(sql);
if (infoList == null || infoList.length < 1)
return null;
return infoList[0];
}

public Hashtable list(String tablename, String id) {
String sql = "select * from " + tablename + " where id ='" + id + "'";
return list(sql);
}

public boolean modify(String tablename, Hashtable setdetail, String filter) {
Enumeration key_values = setdetail.keys();
Statement stmt = null;
String value;
String temp = (String) key_values.nextElement();
value = temp + "='" + setdetail.get(temp) + "'";
while (key_values.hasMoreElements()) {
temp = (String) key_values.nextElement();
value = value + "," + temp + "='" + setdetail.get(temp) + "'";
}
try {
useDB();
stmt = con.createStatement();
sql = "update " + tablename + " set " + value + " where " + filter;
int tag = stmt.executeUpdate(sql);
if (tag == 0)
return false;
else
return true;

} catch (SQLException e) {
System.out.println("执行的出错的sql语句:" + sql);
e.printStackTrace();
return false;
} finally {
closeStmt(stmt);
}
}

public Hashtable[] search(String sql) {
ResultSet rs;
Statement stmt = null;
try {
useDB();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);

return toHashtableArray(rs);
} catch (SQLException ex) {
System.out.println("执行的出错的sql语句:" + sql);
ex.printStackTrace();
return null;
} finally {
closeStmt(stmt);
}
}

public Hashtable[] search(String tablename, String[] fieldname,
String filter) {
return search(tablename, fieldname, filter, "");
}

public Hashtable[] search(String tablename, String[] fieldname,
String filter, String ordergroup) {
ResultSet rs;
Statement stmt = null;
String colname = fieldname[0];

for (int i = 1; i < fieldname.length; i++) {
colname += "," + fieldname[i];
}
String queryString = "select " + colname + " from " + tablename;
if (!filter.equals("")) {
queryString = queryString + " where " + filter;
}
if (!ordergroup.equals("")) {
queryString = queryString + " " + ordergroup;
}
return search(sql);
}

/**
* @return the con
*/
public Connection getCon() {
return con;
}

public void close() {
try {
if (con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

/**
* 返回使用的数据库
*
* @return the dBname
*/
public String getDBname() {
return DBname;
}

/**
* 设置使用的数据库
*
* @param bname
* the dBname to set
*/
public void setDBname(String bname) {
DBname = bname;
}

/**
* 返回执行的sql语句
*
* @return the sql
*/
public String getSql() {
return sql;
}

/**
* 本方法是为了再没有使用连接池的情况下,首先选择使用的数据库。
*/
private void useDB() {
if (DBname != null && DBname.equals("")) {
String query = "use " + DBname;
Statement stmt = null;
try {
stmt = con.createStatement();
stmt.execute(query);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

}
}

/**
* 关闭Statement
*
* @param stmt
*/
private void closeStmt(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

/**
* @param ss
* @return
*/
private String toString(String[] ss) {
String s = "";
for (int i = 0; i < ss.length; i++) {
s += ss[i] + ",";
}
if (s.endsWith(","))
s = s.substring(0, s.length() - 1);
return s;
}

/**
* 把ResultSet转换成Hashtable数组 java.util.Arrays.asList 可以把数组转换成List
*
* @param rs
* @return
*/
private Hashtable[] toHashtableArray(ResultSet rs) {
Vector searchresult = new Vector();
try {
ResultSetMetaData rsmd = rs.getMetaData();
int column = rsmd.getColumnCount();
while (rs.next()) {
Hashtable onerow = new Hashtable();
for (int i = 1; i <= column; i++) {
try {
String columnName = rsmd.getColumnName(i);
String columnValue = rs.getString(columnName);
onerow.put(columnName, columnValue);
} catch (Exception e) {
}
}
searchresult.add(onerow);
}
Hashtable[] searchset = new Hashtable[searchresult.size()];
searchresult.toArray(searchset);
return searchset;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
}

请问如何对用Java对mysql进行增删改查等方法?

package com.ly520.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

/**
* mysql数据库操作类。
*
* @author Ryoma
*
*/
public class MySqlOperate implements SqlOperate {

private Connection con;
private String DBname;
private String sql;

/**
* Mysql数据库初始化包名
*/
private String INIT_SQL_CTX = "org.gjt.mm.mysql.Driver";
/**
* MYSQL数据库服务参数:服务器IP地址和端口
*/
private String SQL_SERVICE = "jdbc:mysql://127.0.0.1:3306?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&mysqlEncoding=utf8";
/**
* MYSQL数据库参数:系统管理用户
*/
private String SQL_SYSTEM_USER = "root";
/**
* MYSQL数据库参数:系统管理密码
*/
private String SQL_SYSTEM_PASSWORD = "123456";

/**
* 初始化链接方法。此方法不需要再使用use Dbname;
*/
public MySqlOperate() {
try {
Context ctx = new InitialContext();
if (ctx == null)
throw new Exception("Boom - No Context");
// java:comp/env/jdbc/imabled_mysql 为配置的连接池的jndi名称。
DataSource ds = (DataSource) ctx
.lookup("java:comp/env/jdbc/imabled_mysql");
con = ds.getConnection();
} catch (Exception ex) {
ex.printStackTrace();
}
}

/**
* 指定库名的连接方法,此方法没有使用连接池,不赞成使用。
*
* @param DBn
*/
public MySqlOperate(String DBn) {
try {
Class.forName(this.INIT_SQL_CTX);

} catch (java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
try {
con = DriverManager.getConnection(this.SQL_SERVICE + "/" + DBn,
this.SQL_SYSTEM_USER, this.SQL_SYSTEM_PASSWORD);
DBname = DBn;
} catch (SQLException ex) {
ex.printStackTrace();
}
}

public boolean add(String tablename, Hashtable searchdetail) {
Statement stmt = null;
Enumeration key_values = searchdetail.keys();
String key, value;
String temp = (String) key_values.nextElement();
key = temp;
value = "'" + searchdetail.get(temp) + "'";
while (key_values.hasMoreElements()) {
temp = (String) key_values.nextElement();
key = key + "," + temp;
value = value + "," + "'" + searchdetail.get(temp) + "'";
}
try {
useDB();
stmt = con.createStatement();
sql = "insert into " + tablename + " (" + key + ") " + " VALUES ("
+ value + ")";
stmt.executeUpdate(sql);
return true;

} catch (SQLException ex) {
System.out.println("执行的出错的sql语句:" + sql);
ex.printStackTrace();
return false;
} finally {
closeStmt(stmt);
}
}

public boolean batchImport(String tablename, List list, String[] fields)
throws SQLException {
PreparedStatement ps = null;
String key, value;
key = toString(fields);
String[] values = new String[fields.length];
for (int i = 0; i < values.length; i++) {
values[i] = "?";
}
value = toString(values);
try {
useDB();
con.setAutoCommit(false);
System.out.println("insert into " + tablename + " (" + key + ") "
+ " VALUES (" + value + ")");
ps = con.prepareStatement("insert into " + tablename + " (" + key
+ ") " + " VALUES (" + value + ")");
String[] tmpData = null;
for (int i = 0; i < list.size(); i++) {
tmpData = (String[]) list.get(i);
for (int j = 0; j < fields.length && j < tmpData.length; j++) {
ps.setString(j + 1, tmpData[j]);
}
ps.addBatch();// 添加执行的语句。
}
int[] count = ps.executeBatch();// 批量执行
con.commit();
return true;
} catch (SQLException ex) {
throw ex;
} finally {
try {
if (ps != null) {
ps.clearParameters();
ps.close();
ps = null;
}
} catch (SQLException e) {
throw e;
}
}
}

public boolean delete(String tablename, String filter) {
Statement stmt = null;
String value;
try {
useDB();
stmt = con.createStatement();
sql = "delete from " + tablename + " where " + filter;
stmt.executeUpdate(sql);
return true;
} catch (SQLException e) {
System.out.println("执行的出错的sql语句:" + sql);
e.printStackTrace();
return false;
} finally {
closeStmt(stmt);
}
}

public Hashtable list(String sql) {
Hashtable[] infoList = search(sql);
if (infoList == null || infoList.length < 1)
return null;
return infoList[0];
}

public Hashtable list(String tablename, String id) {
String sql = "select * from " + tablename + " where id ='" + id + "'";
return list(sql);
}

public boolean modify(String tablename, Hashtable setdetail, String filter) {
Enumeration key_values = setdetail.keys();
Statement stmt = null;
String value;
String temp = (String) key_values.nextElement();
value = temp + "='" + setdetail.get(temp) + "'";
while (key_values.hasMoreElements()) {
temp = (String) key_values.nextElement();
value = value + "," + temp + "='" + setdetail.get(temp) + "'";
}
try {
useDB();
stmt = con.createStatement();
sql = "update " + tablename + " set " + value + " where " + filter;
int tag = stmt.executeUpdate(sql);
if (tag == 0)
return false;
else
return true;

} catch (SQLException e) {
System.out.println("执行的出错的sql语句:" + sql);
e.printStackTrace();
return false;
} finally {
closeStmt(stmt);
}
}

public Hashtable[] search(String sql) {
ResultSet rs;
Statement stmt = null;
try {
useDB();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);

return toHashtableArray(rs);
} catch (SQLException ex) {
System.out.println("执行的出错的sql语句:" + sql);
ex.printStackTrace();
return null;
} finally {
closeStmt(stmt);
}
}

public Hashtable[] search(String tablename, String[] fieldname,
String filter) {
return search(tablename, fieldname, filter, "");
}

public Hashtable[] search(String tablename, String[] fieldname,
String filter, String ordergroup) {
ResultSet rs;
Statement stmt = null;
String colname = fieldname[0];

for (int i = 1; i < fieldname.length; i++) {
colname += "," + fieldname[i];
}
String queryString = "select " + colname + " from " + tablename;
if (!filter.equals("")) {
queryString = queryString + " where " + filter;
}
if (!ordergroup.equals("")) {
queryString = queryString + " " + ordergroup;
}
return search(sql);
}

/**
* @return the con
*/
public Connection getCon() {
return con;
}

public void close() {
try {
if (con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

/**
* 返回使用的数据库
*
* @return the dBname
*/
public String getDBname() {
return DBname;
}

/**
* 设置使用的数据库
*
* @param bname
* the dBname to set
*/
public void setDBname(String bname) {
DBname = bname;
}

/**
* 返回执行的sql语句
*
* @return the sql
*/
public String getSql() {
return sql;
}

/**
* 本方法是为了再没有使用连接池的情况下,首先选择使用的数据库。
*/
private void useDB() {
if (DBname != null && DBname.equals("")) {
String query = "use " + DBname;
Statement stmt = null;
try {
stmt = con.createStatement();
stmt.execute(query);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

}
}

/**
* 关闭Statement
*
* @param stmt
*/
private void closeStmt(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

/**
* @param ss
* @return
*/
private String toString(String[] ss) {
String s = "";
for (int i = 0; i < ss.length; i++) {
s += ss[i] + ",";
}
if (s.endsWith(","))
s = s.substring(0, s.length() - 1);
return s;
}

/**
* 把ResultSet转换成Hashtable数组 java.util.Arrays.asList 可以把数组转换成List
*
* @param rs
* @return
*/
private Hashtable[] toHashtableArray(ResultSet rs) {
Vector searchresult = new Vector();
try {
ResultSetMetaData rsmd = rs.getMetaData();
int column = rsmd.getColumnCount();
while (rs.next()) {
Hashtable onerow = new Hashtable();
for (int i = 1; i <= column; i++) {
try {
String columnName = rsmd.getColumnName(i);
String columnValue = rs.getString(columnName);
onerow.put(columnName, columnValue);
} catch (Exception e) {
}
}
searchresult.add(onerow);
}
Hashtable[] searchset = new Hashtable[searchresult.size()];
searchresult.toArray(searchset);
return searchset;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
}

mysql与java连接实现增删改 数据库数据。我写了连接的代码如下,请帮我补充下被,或者发整个代码也行。

public static Connection GetJDBCConn() {

Connection conn = null;

try {

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

try {

conn = DriverManager.getConnection(ur1,user,password);

} catch (SQLException e) {

e.printStackTrace();

}

return conn;

}

急 用java写一个 连接数据库 增删改的例子

DBConnectionManager.java //连接数据库用的

import java.sql.*;

public class DBConnectionManager {

private String driverName="com.microsoft.jdbc.sqlserver.SQLServerDriver";

private String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=demo";

private String user="sa";

private String password="";

public String getDriverName() {

return driverName;

}

public void setDriverName(String driverName) {

this.driverName = driverName;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public String getUrl() {

return url;

}

public void setUrl(String url) {

this.url = url;

}

public String getUser() {

return user;

}

public void setUser(String user) {

this.user = user;

}

public Connection getConnection(){

try{

Class.forName(driverName);

return DriverManager.getConnection(url, user, password);

}catch(Exception e){

e.printStackTrace();

return null;

}

}

}

DBSQLManager.java //操作数据库用的

import java.sql.*;

public class DBSQLManager {

protected Connection con=null;//Connection对象

protected Statement stmt=null;//Statement对象

protected ResultSet rs=null;//记录结果集

protected String sql=""; //SQL语句

public DBSQLManager(){

try {

DBConnectionManager dcm=new DBConnectionManager();

con=dcm.getConnection();

//con.setAutoCommit(false);//添加事物,既是否自动提交

stmt=con.createStatement();

} catch (SQLException e) {

e.printStackTrace();

}

}

public Statement getStmt(){

return stmt;

}

public Connection getCon(){

return con;

}

public ResultSet getRs(){

return rs;

}

public void setSql(String sql){

this.sql=sql;

}

public String getSql(){

return sql;

}

//查找

public void execueQuery(){

try {

rs=stmt.executeQuery(sql);

} catch (SQLException e) {

e.printStackTrace();

}

}

//更新

public void executeUpdate(){

try {

stmt.executeUpdate(sql);

} catch (SQLException e) {

e.printStackTrace();

}

}

//关闭

public void close(){

if(rs!=null){

try {

rs.close();

} catch (SQLException e) {

e.printStackTrace();

}

rs=null;

}

if(stmt!=null){

try {

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

stmt=null;

}

try {

con.close();

} catch (SQLException e) {

e.printStackTrace();

}

con=null;

}

}

SqlOperate.java //用来调用数据库操作语句

import java.sql.ResultSet;

import java.sql.SQLException;

public class SqlOperate {

//插入,修改,删除

public void insOrModOrDel(String sql){

DBSQLManager dbsm=new DBSQLManager();

dbsm.getStmt();

dbsm.setSql(sql);

dbsm.executeUpdate();

dbsm.close();

}

//显示

public void display(String sql){

DBSQLManager dbsm=new DBSQLManager();

dbsm.getStmt();

dbsm.setSql(sql);

dbsm.execueQuery();

ResultSet rs=dbsm.getRs();

try {

while(rs!=null&&rs.next()){

System.out.print(rs.getObject(1)+"\t");

System.out.print(rs.getObject(2)+"\t");

System.out.print(rs.getObject(3)+"\t");

System.out.println(rs.getObject(4));

}

dbsm.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

SqlMain.java //数据库的测试主函数

public class SqlMain {

public static void main(String[] args){

SqlOperate sqlOpt=new SqlOperate();

// sqlOpt.insOrModOrDel("insert into user1 values('qianhaifei',999999,'qianhaifei@163.com')");//插入

// sqlOpt.insOrModOrDel("update user1 set username='weixiangyang' where id=4");//修改

// sqlOpt.insOrModOrDel("delete from user1 where username='weixy2000'");//删除

sqlOpt.display("select *from user1");//显示

}

}

楼主用的时间只需要将数据库 用户名和密码还有数据库表名改一下就行了...

其他都是一样的...

楼主会改吧.../???

如果有什么问题的话请百度HI我...帮你解决....

如果楼主要我的数据库的话....请百度HI我...我给你就行了...

祝楼主早日成功!

Top