java操作mysql增删改查

来源:互联网 发布:企业局域网监控软件 编辑:程序博客网 时间:2024/06/05 18:34

用到的架包:mysql-connector-java-5.1.13-bin.jar  网上可以自己搜索下下载就行了。

数据库:
CREATE TABLE `ceshi` (
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `number` int(11) NOT NULL,
   `money` double(10,2) NOT NULL,
   `score` float(10,2) NOT NULL,
   `username` varchar(20) NOT NULL,
   PRIMARY KEY (`id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
 
 实体类:
 package com.test.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @ClassName: TestSql
 *
 * @Description: 测试sql链接数据库
 * @author PineTree
 * @date 2014年11月29日 下午11:29:42
 *
 */
public class TestSql {
 // 链接mysql数据库固定写法
 private String dbDriver = "com.mysql.jdbc.Driver";
 // jdbc:mysql://[ip地址]:[端口号]/[数据库名]?characterEncoding=[数据库编码格式,我的是utf-8,具体的格式根据自己的数据库格式来]";
 private String dbUrl = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8";// 根据实际情况变化
 // 账号,这里改成你自己的帐号
 private String dbUser = "root";
 // 密码,这里改成你自己的密码
 private String dbPass = "sp308036654";

 public static void main(String[] args) {
  // 测试
  TestSql ts = new TestSql();
  //ts.insert();// 添加
  //ts.update();// 删除
  //ts.select();// 查询
  ts.delete();// 修改
 }

 /**
  *
  * @Description: 建立sql链接
  *
  * @return Connection
  */
 public Connection getConn() {
  Connection conn = null;
  try {
   Class.forName(dbDriver).newInstance();
   conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);// 注意是三个参数
  } catch (ClassNotFoundException ce) {
   ce.printStackTrace();
  } catch (SQLException se) {
   se.printStackTrace();
  } catch (InstantiationException ite) {
   // TODO Auto-generated catch block
   ite.printStackTrace();
  } catch (IllegalAccessException iae) {
   iae.printStackTrace();
  }
  return conn;
 }

 /**
  *
  * @Description: 往数据库中某个表中添加数据
  *
  * @return int
  */
 public int insert() {
  int i = 0;
  // sql语句 insert into (表名)(列名1, 列名2, 列名3, 列名4, 列名5) values(?, ?, ?, ?, ?)";
  String sql = "insert into ceshi(id, number, money, score, username) values(?, ?, ?, ?, ?)";
  Connection con = getConn();
  PreparedStatement preStmt = null;
  try {
   preStmt = con.prepareStatement(sql);
   // preStmt.setXXX(数字,你传进来的值) 提示:setXXX 类型要根据你定义的类型来
   preStmt.setInt(1, 1);// 这里是从1开始,不是从零开始切记,如果数据库主键自增可以不添加主键
   preStmt.setInt(2, 12);
   preStmt.setDouble(3, 10.6);
   preStmt.setFloat(4, (float) 2.1);
   preStmt.setString(5, "李四");
   i = preStmt.executeUpdate();
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   // 使用完就得关闭流,释放资源
   try {
    if (con != null) con.close(); 
    if (preStmt != null) preStmt.close(); 
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return i;// 返回影响的行数,不为0执行成功
 }

 /**
  *
  * @Description: 修改数据库中某个数据表的某个数据
  *
  * @return int
  */
 public int update() {
  int i = 0;
  // sql语句 update (表名) set (列名1) = ?, , (列名2) = ?, (列名3) = ?, (列名4) = ? where (列名1)=?
  //提示:注意要有where条件,具体如下
  String sql = "update ceshi set number =? , money = ? , score = ? , username = ? where id= ?";
  Connection con = getConn();
  PreparedStatement preStmt = null;
  try {
   preStmt = con.prepareStatement(sql);
   preStmt.setInt(1, 123);
   preStmt.setDouble(2, 73.25);
   preStmt.setFloat(3, (float) 1.2);
   preStmt.setString(4, "张三");
   preStmt.setInt(5, 3);
   i = preStmt.executeUpdate();
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   // 使用完就得关闭流,释放资源
   try {
    if (con != null) con.close(); 
    if (preStmt != null) preStmt.close(); 
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return i;// 返回影响的行数,1为执行成功
 }

 /**
  *
  * @Description: 查寻数据库数据
  *
  * @return String
  */
 public String select() {
  String sql = "select * from ceshi";
  Connection con = getConn();// 此处为通过自己写的方法getConn()获得连接
  Statement stmt = null;
  ResultSet rs = null;
  try {
   stmt = con.createStatement();
   rs = stmt.executeQuery(sql);

   while(rs.next()) {
    System.out.println("查找到的值:" + rs.getRow()  + "\ttid = " + rs.getInt(1)
        + "\tnumber = " + rs.getInt(2) + "\tmoney = "
        + rs.getDouble(3) + "\tscore = "
        + rs.getFloat("score"));
   }
   // 可以将查找到的值写入类,然后返回相应的对象
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   // 使用完就得关闭流,释放资源
   try {
    if (con != null) con.close(); 
    if (stmt != null) stmt.close(); 
    if (rs != null) rs.close(); 
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return "success"; //具体返回根据个人业务而定
 }

 /**
  *
  * @Description: 删除数数据库中某个表符合条件的数据
  *
  * @return int
  */
 public int delete() {
  // sql语句 delete from (表名) where (列名)=(值)
  String sql = "delete from ceshi where id = 5";
  int i = 0;
  Connection con = getConn();// 此处为通过自己写的方法getConn()获得连接
  Statement stmt = null;
  try {
   stmt = con.createStatement();
   i = stmt.executeUpdate(sql);
  } catch (SQLException e) {
   e.printStackTrace();
  }finally{
   try{
    if(con != null) con.close();
    if(stmt != null) stmt.close();
   }catch(Exception e){
    e.printStackTrace();
   }
  }
  return i;// 如果返回的是1,则执行成功;
 }
}

提示:如果报
package com.test.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @ClassName: TestSql
 *
 * @Description: 测试sql链接数据库
 * @author PineTree
 * @date 2014年11月29日 下午11:29:42
 *
 */
public class TestSql {
 // 链接mysql数据库固定写法
 private String dbDriver = "com.mysql.jdbc.Driver";
 // jdbc:mysql://[ip地址]:[端口号]/[数据库名]?characterEncoding=[数据库编码格式,我的是utf-8,具体的格式根据自己的数据库格式来]";
 private String dbUrl = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8";// 根据实际情况变化
 // 账号,这里改成你自己的帐号
 private String dbUser = "root";
 // 密码,这里改成你自己的密码
 private String dbPass = "sp308036654";

 public static void main(String[] args) {
  // 测试
  TestSql ts = new TestSql();
  //ts.insert();// 添加
  //ts.update();// 删除
  //ts.select();// 查询
  ts.delete();// 修改
 }

 /**
  *
  * @Description: 建立sql链接
  *
  * @return Connection
  */
 public Connection getConn() {
  Connection conn = null;
  try {
   Class.forName(dbDriver).newInstance();
   conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);// 注意是三个参数
  } catch (ClassNotFoundException ce) {
   ce.printStackTrace();
  } catch (SQLException se) {
   se.printStackTrace();
  } catch (InstantiationException ite) {
   // TODO Auto-generated catch block
   ite.printStackTrace();
  } catch (IllegalAccessException iae) {
   iae.printStackTrace();
  }
  return conn;
 }

 /**
  *
  * @Description: 往数据库中某个表中添加数据
  *
  * @return int
  */
 public int insert() {
  int i = 0;
  // sql语句 insert into (表名)(列名1, 列名2, 列名3, 列名4, 列名5) values(?, ?, ?, ?, ?)";
  String sql = "insert into ceshi(id, number, money, score, username) values(?, ?, ?, ?, ?)";
  Connection con = getConn();
  PreparedStatement preStmt = null;
  try {
   preStmt = con.prepareStatement(sql);
   // preStmt.setXXX(数字,你传进来的值) 提示:setXXX 类型要根据你定义的类型来
   preStmt.setInt(1, 1);// 这里是从1开始,不是从零开始切记,如果数据库主键自增可以不添加主键
   preStmt.setInt(2, 12);
   preStmt.setDouble(3, 10.6);
   preStmt.setFloat(4, (float) 2.1);
   preStmt.setString(5, "李四");
   i = preStmt.executeUpdate();
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   // 使用完就得关闭流,释放资源
   try {
    if (con != null) con.close(); 
    if (preStmt != null) preStmt.close(); 
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return i;// 返回影响的行数,不为0执行成功
 }

 /**
  *
  * @Description: 修改数据库中某个数据表的某个数据
  *
  * @return int
  */
 public int update() {
  int i = 0;
  // sql语句 update (表名) set (列名1) = ?, , (列名2) = ?, (列名3) = ?, (列名4) = ? where (列名1)=?
  //提示:注意要有where条件,具体如下
  String sql = "update ceshi set number =? , money = ? , score = ? , username = ? where id= ?";
  Connection con = getConn();
  PreparedStatement preStmt = null;
  try {
   preStmt = con.prepareStatement(sql);
   preStmt.setInt(1, 123);
   preStmt.setDouble(2, 73.25);
   preStmt.setFloat(3, (float) 1.2);
   preStmt.setString(4, "张三");
   preStmt.setInt(5, 3);
   i = preStmt.executeUpdate();
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   // 使用完就得关闭流,释放资源
   try {
    if (con != null) con.close(); 
    if (preStmt != null) preStmt.close(); 
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return i;// 返回影响的行数,1为执行成功
 }

 /**
  *
  * @Description: 查寻数据库数据
  *
  * @return String
  */
 public String select() {
  String sql = "select * from ceshi";
  Connection con = getConn();// 此处为通过自己写的方法getConn()获得连接
  Statement stmt = null;
  ResultSet rs = null;
  try {
   stmt = con.createStatement();
   rs = stmt.executeQuery(sql);

   while(rs.next()) {
    System.out.println("查找到的值:" + rs.getRow()  + "\ttid = " + rs.getInt(1)
        + "\tnumber = " + rs.getInt(2) + "\tmoney = "
        + rs.getDouble(3) + "\tscore = "
        + rs.getFloat("score"));
   }
   // 可以将查找到的值写入类,然后返回相应的对象
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   // 使用完就得关闭流,释放资源
   try {
    if (con != null) con.close(); 
    if (stmt != null) stmt.close(); 
    if (rs != null) rs.close(); 
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return "success"; //具体返回根据个人业务而定
 }

 /**
  *
  * @Description: 删除数数据库中某个表符合条件的数据
  *
  * @return int
  */
 public int delete() {
  // sql语句 delete from (表名) where (列名)=(值)
  String sql = "delete from ceshi where id = 5";
  int i = 0;
  Connection con = getConn();// 此处为通过自己写的方法getConn()获得连接
  Statement stmt = null;
  try {
   stmt = con.createStatement();
   i = stmt.executeUpdate(sql);
  } catch (SQLException e) {
   e.printStackTrace();
  }finally{
   try{
    if(con != null) con.close();
    if(stmt != null) stmt.close();
   }catch(Exception e){
    e.printStackTrace();
   }
  }
  return i;// 如果返回的是1,则执行成功;
 }

}
package com.test.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @ClassName: TestSql
 *
 * @Description: 测试sql链接数据库
 * @author PineTree
 * @date 2014年11月29日 下午11:29:42
 *
 */
public class TestSql {
 // 链接mysql数据库固定写法
 private String dbDriver = "com.mysql.jdbc.Driver";
 // jdbc:mysql://[ip地址]:[端口号]/[数据库名]?characterEncoding=[数据库编码格式,我的是utf-8,具体的格式根据自己的数据库格式来]";
 private String dbUrl = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8";// 根据实际情况变化
 // 账号,这里改成你自己的帐号
 private String dbUser = "root";
 // 密码,这里改成你自己的密码
 private String dbPass = "sp308036654";

 public static void main(String[] args) {
  // 测试
  TestSql ts = new TestSql();
  //ts.insert();// 添加
  //ts.update();// 删除
  //ts.select();// 查询
  ts.delete();// 修改
 }

 /**
  *
  * @Description: 建立sql链接
  *
  * @return Connection
  */
 public Connection getConn() {
  Connection conn = null;
  try {
   Class.forName(dbDriver).newInstance();
   conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);// 注意是三个参数
  } catch (ClassNotFoundException ce) {
   ce.printStackTrace();
  } catch (SQLException se) {
   se.printStackTrace();
  } catch (InstantiationException ite) {
   // TODO Auto-generated catch block
   ite.printStackTrace();
  } catch (IllegalAccessException iae) {
   iae.printStackTrace();
  }
  return conn;
 }

 /**
  *
  * @Description: 往数据库中某个表中添加数据
  *
  * @return int
  */
 public int insert() {
  int i = 0;
  // sql语句 insert into (表名)(列名1, 列名2, 列名3, 列名4, 列名5) values(?, ?, ?, ?, ?)";
  String sql = "insert into ceshi(id, number, money, score, username) values(?, ?, ?, ?, ?)";
  Connection con = getConn();
  PreparedStatement preStmt = null;
  try {
   preStmt = con.prepareStatement(sql);
   // preStmt.setXXX(数字,你传进来的值) 提示:setXXX 类型要根据你定义的类型来
   preStmt.setInt(1, 1);// 这里是从1开始,不是从零开始切记,如果数据库主键自增可以不添加主键
   preStmt.setInt(2, 12);
   preStmt.setDouble(3, 10.6);
   preStmt.setFloat(4, (float) 2.1);
   preStmt.setString(5, "李四");
   i = preStmt.executeUpdate();
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   // 使用完就得关闭流,释放资源
   try {
    if (con != null) con.close(); 
    if (preStmt != null) preStmt.close(); 
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return i;// 返回影响的行数,不为0执行成功
 }

 /**
  *
  * @Description: 修改数据库中某个数据表的某个数据
  *
  * @return int
  */
 public int update() {
  int i = 0;
  // sql语句 update (表名) set (列名1) = ?, , (列名2) = ?, (列名3) = ?, (列名4) = ? where (列名1)=?
  //提示:注意要有where条件,具体如下
  String sql = "update ceshi set number =? , money = ? , score = ? , username = ? where id= ?";
  Connection con = getConn();
  PreparedStatement preStmt = null;
  try {
   preStmt = con.prepareStatement(sql);
   preStmt.setInt(1, 123);
   preStmt.setDouble(2, 73.25);
   preStmt.setFloat(3, (float) 1.2);
   preStmt.setString(4, "张三");
   preStmt.setInt(5, 3);
   i = preStmt.executeUpdate();
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   // 使用完就得关闭流,释放资源
   try {
    if (con != null) con.close(); 
    if (preStmt != null) preStmt.close(); 
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return i;// 返回影响的行数,1为执行成功
 }

 /**
  *
  * @Description: 查寻数据库数据
  *
  * @return String
  */
 public String select() {
  String sql = "select * from ceshi";
  Connection con = getConn();// 此处为通过自己写的方法getConn()获得连接
  Statement stmt = null;
  ResultSet rs = null;
  try {
   stmt = con.createStatement();
   rs = stmt.executeQuery(sql);

   while(rs.next()) {
    System.out.println("查找到的值:" + rs.getRow()  + "\ttid = " + rs.getInt(1)
        + "\tnumber = " + rs.getInt(2) + "\tmoney = "
        + rs.getDouble(3) + "\tscore = "
        + rs.getFloat("score"));
   }
   // 可以将查找到的值写入类,然后返回相应的对象
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   // 使用完就得关闭流,释放资源
   try {
    if (con != null) con.close(); 
    if (stmt != null) stmt.close(); 
    if (rs != null) rs.close(); 
   } catch (Exception e) {
    e.printStackTrace();
   }
  }
  return "success"; //具体返回根据个人业务而定
 }

 /**
  *
  * @Description: 删除数数据库中某个表符合条件的数据
  *
  * @return int
  */
 public int delete() {
  // sql语句 delete from (表名) where (列名)=(值)
  String sql = "delete from ceshi where id = 5";
  int i = 0;
  Connection con = getConn();// 此处为通过自己写的方法getConn()获得连接
  Statement stmt = null;
  try {
   stmt = con.createStatement();
   i = stmt.executeUpdate(sql);
  } catch (SQLException e) {
   e.printStackTrace();
  }finally{
   try{
    if(con != null) con.close();
    if(stmt != null) stmt.close();
   }catch(Exception e){
    e.printStackTrace();
   }
  }
  return i;// 如果返回的是1,则执行成功;
 }

}


提示:如果报Incorrect string value: '\\xE6\\xB7\\xB1\\xE5\\x85\\xA5...' for column 'xxx' at row xxx,
一、看看你创建的mysql数据库是否为你实体类里dbUrl链接数据库写的编码格式一致,如果不一致修改你的实体类dbUrl后的编码或者修改数据库。
二、如果上面不行,修改你的mysql目录里的 X盘:\xxx\mysql\my.ini文件中的 default-character-set=你的编码格式。
三、如果上面还不行,查看数据库校验规则,和你的表的校验规则。
四、如果上面都不行,重新建个数据库,编码格式一定要设置好。

0 0