mysql标准代码
2019-01-17 本文已影响6人
Frank_8942
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
public class MysqlDemo {
public static String url = "jdbc:mysql://localhost:3306/test";
public static String user = "root";
public static String password = "root";
public static String driver = "com.mysql.jdbc.Driver";
public static void main(String[] args) {
String sql = "select * from test.emp ";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
ArrayList<Entity> entities = new ArrayList<Entity>();
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,user,password);
conn.setAutoCommit(false);
ps = conn.prepareStatement(sql);
rs= ps.executeQuery();
while (rs.next()){
Entity entity = new Entity();
entity.setEmpno( rs.getString("empno") );
entity.setEname( rs.getString("ename") );
entity.setJob( rs.getString("job"));
entity.setSal( rs.getDouble("sal"));
entity.setHiredate( new Date(rs.getDate("hiredate").getTime()) );
entities.add(entity);
}
conn.commit();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null){
ps.close();
}
if (conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
for(Entity temp:entities){
System.out.println(temp);
}
}
public static class Entity{
public String empno;
public String ename;
public String job;
public Date hiredate;
public double sal;
@Override
public String toString() {
return "Entity{" +
"empno='" + empno + '\'' +
", ename='" + ename + '\'' +
", job='" + job + '\'' +
", hiredate=" + hiredate +
", sal=" + sal +
'}';
}
public String getEmpno() {
return empno;
}
public void setEmpno(String empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
}
}