此次开发工具为eclipse,才有的数据库驱动是mysql-connector-java-5.1.8-bin.jar
第一步,在eclipse的工程目录中引用mysql驱动
驱动下载地址:https://dev.mysql.com/downloads/connector/j/
选择build path 然后选择configure build path
再选择libraries,选择add external library,找到之前下的数据库驱动,确认,ok
然后下一段测试代码将数据库驱动起来
public class test { public static void main(String []args) { try { //mysql数据库设置驱动程序类型 Class.forName("com.mysql.jdbc.Driver"); System.out.println("mysql数据库驱动加载成功"); } catch(ClassNotFoundException e) { e.printStackTrace(); } } }
驱动代码运行一次就行了,之后就是操作数据库了
基本操作增改删查,原理都是一样的
先创建一个Connection对象
Connection connection = null; String user="root";//用户名 String password="19980713";//密码 String url = "jdbc:mysql://localhost:3306/task?user="+user+"&password="+password+"&useUnicode=true&characterEncoding=utf-8";//获得连接的语句 try{ connection = (Connection)DriverManager.getConnection(url); }catch(SQLException e){ e.printStackTrace(); }
获得连接之后就是对connection进行操作了
查询记录
String sql = "select id,name,job,department,state,authority from worker;"; try { PreparedStatement ps = (PreparedStatement) connection.prepareStatement(sql);//预编译过程 ResultSet rs = ps.executeQuery();//查询一般用executeQuery,返回的是查询的结果集 //下面是对结果集进行操作 while(rs.next()) { count++; Vector v = new Vector(); v.add((rs.getString(1))); v.add((rs.getString(2))); v.add((rs.getString(3))); v.add((rs.getString(4))); v.add((rs.getString(5))); v.add((rs.getString(6))); worker.add(v); } }catch(SQLException e1) { e1.printStackTrace(); }
插入记录
String sql = "insert into worker(name) " +"value("+ ""\"小明"\"" + ")"; PreparedStatement ps = (PreparedStatement) connection.prepareStatement(sql); try { PreparedStatement ps = (PreparedStatement) connection.prepareStatement(sql); if(ps.executeUpdate()==1){//返回一个int值表示返回的条数 int n = JOptionPane.showConfirmDialog(null, "添加成功,是否继续添加?", "系统提示",JOptionPane.YES_NO_OPTION); if(n == 0){ //清空面板 name.setText(""); sex.setText(""); authority.setText(""); birthday.setText(""); department.setText(""); job.setText(""); email.setText(""); state.setText(""); remark.setText(""); specialty.setText(""); address.setText(""); tel.setText(""); edu_level.setText(""); }else{ dispose(); JoinNewMember frame = new JoinNewMember(); } } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }
其余操作就不贴代码了,以此类推就是的,我先准备一下六级去了,要不待会再来更新
原文地址:https://www.cnblogs.com/Yintianhao/p/9190110.html
时间: 2024-10-13 16:16:18