JDBC操作Mysql数据库源代码

来源:互联网 发布:java获取磁盘io 编辑:程序博客网 时间:2024/06/07 16:05

import java.sql.Connection;import java.sql.DriverManager;//打开并连接数据库public class TestCon {public static Connection getMySQLCon() {Connection con = null;try {Class.forName("com.mysql.jdbc.Driver");String user = "root";String pwd = "admin";String url = "jdbc:mysql://localhost:3306/mysql";con = DriverManager.getConnection(url, user, pwd);} catch (Exception e) {e.printStackTrace();}return con;}public static void main(String[] args) {Connection conn = TestCon.getMySQLCon();if (conn != null) {System.out.println("MySql链接成功!Connection=" + conn.toString());}}}//操作数据库:import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import java.sql.*;//import com.mysql.jdbc.Statement;public class EmployeeDao {private static EmployeeDao instance = null;public static EmployeeDao getInstance() {if (instance == null) {instance = new EmployeeDao();}return instance;}//插入员工信息数据public boolean saveEmployee(Employee emp) {boolean result = false;Connection con = null;try {con = DBcon.getConn();String sql = "insert into employee(empName,empAge,empSex,empDuty,empId) values(?,?,?,?,?)";PreparedStatement stmt = con.prepareStatement(sql);stmt.setString(1, emp.getEmpName());stmt.setInt(2, emp.getEmpAge());stmt.setString(3, emp.getEmpSex());stmt.setString(4, emp.getEmpDuty());stmt.setInt(5, emp.getEmpId());int i = stmt.executeUpdate();if (i == 1) {result = true;}} catch (Exception e) {e.printStackTrace();} finally {try {con.close();} catch (SQLException e) {e.printStackTrace();}}return result;}//获取员工信息数据public List<Employee> selectEmployee() {List<Employee> empList = new ArrayList<Employee>();Connection conn = null;try {conn = DBcon.getConn();Statement stmt = conn.createStatement();ResultSet rst = stmt.executeQuery("select *from employee");while (rst.next()) {Employee emp = new Employee();emp.setEmpId(rst.getInt("empId"));emp.setEmpName(rst.getString("empName"));emp.setEmpAge(rst.getInt("empAge"));emp.setEmpDuty(rst.getString("empDuty"));empList.add(emp);}} catch (Exception e) {e.printStackTrace();} finally {try {conn.close();} catch (Exception e) {e.getStackTrace();}}return empList;}}