jdbc mysql源代码_JDBC操作Mysql数据库源代码

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 selectEmployee() {

List empList = new ArrayList();

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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值