logo资料库

JDBC MySQL 连接配置+操作.docx

第1页 / 共3页
第2页 / 共3页
第3页 / 共3页
资料共3页,全文预览结束
MySQL 数据库 端口号:3306 数据库名称:sqltestdb 用户名:root 数据包名称:emp 密码:root 连接配置 package sqldemo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class main { public static void main(String[] args) { //声明 Connection 对象 Connection con; //驱动程序名 String driver = "com.mysql.jdbc.Driver"; //URL 指向要访问的数据库名 mydata String url = "jdbc:mysql://localhost:3306/sqltestdb"; //MySQL 配置时的用户名 String user = "root"; //MySQL 配置时的密码 String password = "123456"; //遍历查询结果集 try { //加载驱动程序 Class.forName(driver); //1.getConnection()方法,连接 MySQL 数据库!! con = DriverManager.getConnection(url,user,password); if(!con.isClosed()) System.out.println("Succeeded connecting to the Database!"); // 这里填写你的要执行的 sql 语句 //执行完需要关闭连接 节省资源 rs.close(); con.close(); } catch(ClassNotFoundException e) { //数据库驱动类异常处理 System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); } catch(SQLException e) { //数据库连接失败异常处理
e.printStackTrace(); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ System.out.println("数据库连接进行 sql 语句操作!!"); } } } sql 查询语句 //创建 statement 类对象,用来执行 SQL 语句!! Statement statement = con.createStatement(); //要执行的 SQL 语句 String sql = "select * from emp"; //3.ResultSet 类,用来存放获取的结果集!! ResultSet rs = statement.executeQuery(sql); System.out.println("-----------------"); System.out.println("执行结果如下所示:"); System.out.println("-----------------"); System.out.println("姓名" + "\t" + "职称"); System.out.println("-----------------"); String job = null; String id = null; while(rs.next()){ //获取 stuname 这列数据 job = rs.getString("job"); //获取 stuid 这列数据 id = rs.getString("ename"); //输出结果 System.out.println(id + "\t" + job); } 增加数据: String name; String id; PreparedStatement psql; ResultSet res; //预处理添加数据,其中有两个参数--“?”
psql = con.prepareStatement("insert into emp (empno,ename,job,hiredate,sal) " + "values(?,?,?,?,?)"); psql.setInt(1, 3212); //设置参数 1,创建 id 为 3212 的数据 psql.setString(2, "王刚"); //设置参数 2,name 为王刚 psql.setString(3, "总裁"); DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd"); Date myDate2 = dateFormat2.parse("2010-09-13"); psql.setDate(4,new java.sql.Date(myDate2.getTime())); psql.setFloat(5, (float) 2000.3); psql.executeUpdate(); //执行更新 更新数据 PreparedStatement psql; //预处理更新(修改)数据,将王刚的 sal 改为 5000.0 psql = con.prepareStatement("update emp set sal = ? where ename = ?"); psql.setFloat(1,(float) 5000.0); psql.setString(2,"王刚"); psql.executeUpdate(); 删除数据 PreparedStatement psql; //预处理删除数据 psql = con.prepareStatement("delete from emp where sal = ?"); psql.setFloat(1, 4500); psql.executeUpdate(); psql.close();
分享到:
收藏