1、下载连接驱动:mysql-connector-java-5.1.26-bin.jar。
2、导入到项目中,以Eclipse为例:
a、在项目上右键--Build Path--Configure Build Path--Libraries--Add External JARs...---导入下载的连接驱动,结果如图
3、在mysql中创建数据库和表,如下test数据库和admin表,
表中数据如下:
4、写代码,连接数据库:
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; //数据库连接类 public class DBHelper { public static final String url = "jdbc:mysql://localhost/test"; public static final String name = "com.mysql.jdbc.Driver"; public static final String user = "root"; public static final String password = "root"; public Connection conn = null; public PreparedStatement st = null; public DBHelper(){ try { Class.forName(name); conn = DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public void close(){ try { this.conn.close(); this.st.close(); } catch (Exception e) { System.out.println("关闭数据链接出错!"); } } }
测试类:
package dao; import java.sql.ResultSet; import java.sql.SQLException; public class Demo { public DBHelper db = new DBHelper(); public ResultSet rs = null; public static void main(String[] args){ Demo d = new Demo(); // d.insertAdmin("xl", "xl"); // d.delectName("xl"); // d.updateName("xl", "123"); d.selectAll(); } /* * 增加记录 * @name 账号 * @password 密码 * @return 成功与否 * */ public boolean insertAdmin(String name, String password){ String sql = "insert into admin(name,password) values(?,?)"; try { db.st = db.conn.prepareStatement(sql); db.st.setString(1, name); db.st.setString(2, password); return db.st.execute(); } catch (SQLException e) { e.printStackTrace(); } return false; } /* * 查找所有记录 * */ public void selectAll(){ String sql = "select * from admin"; try { db.st = db.conn.prepareStatement(sql); rs = db.st.executeQuery(); while(rs.next()){ int id = rs.getInt(1); String name = rs.getString(2); String password = rs.getString(3); System.out.println("id:"+id+" name:"+name+" password:"+password); } } catch (SQLException e) { e.printStackTrace(); } } /* * 根据账号,删除信息 * @name 账号 * @return 成功与否 * */ public boolean delectName(String name){ String sql = "delete from admin where name = ?"; try { db.st = db.conn.prepareStatement(sql); db.st.setString(1, name); return db.st.execute(); } catch (SQLException e) { e.printStackTrace(); } return false; } /* * 根据账号,修改密码 * @name 账号 * @password 要修改的密码 * @return 成功与否 * */ public int updateName(String name,String password){ String sql = "update admin set password = ? where name = ?"; try { db.st = db.conn.prepareStatement(sql); db.st.setString(1, password); db.st.setString(2, name); return db.st.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } return 0; } }