JDBC的连接:
String driverClassName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mytb";
String username = "root";
String password = "123";
Class.forName(driverClassName);
Connection con = DriverManager.getConnection(url, username, password);
//System.out.println(con);
1、JDBC的增删改:
Statement sta = con.createStatement();
String sql = "insert into stu values('xiaohong','woman',22,'0010')";
int r = sta.executeUpdate(sql);
2、JDBC的查寻:
Statement sta = con.createStatement();
ResultSet res = sta.executeQuery("select * from emp");
while(res.next()){
int empno = res.getInt(1); //得到表的内容
String ename = res.getString("ename");
String job = res.getString("job");
int mg = res.getInt("mgr");
Date hiredate = res.getDate("hiredate");
double sal = res.getDouble("sal");
double COMM = res.getDouble("COMM");
int deptno = res.getInt("deptno");
System.out.println(""+empno+" , "+ename+" , "+job+" , "+mg+" , "+hiredate+" , "+sal+" , "+COMM+" , "+deptno);
}
3、JDBC的关闭:
sta.close();
con.close();
规范样式:
@Test
public void fun() throws Exception {
Connection con = null;
Statement sta = null;
ResultSet res = null;
try {
String driverClassName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mytb";
String username = "root";
String password = "123";
Class.forName(driverClassName);
con = DriverManager.getConnection(url, username, password);
sta = con.createStatement();
String sql = "select * from stu";
res = sta.executeQuery(sql);
while (res.next()) {
System.out.println(res.getObject(1) + " " + res.getObject(2)
+ " " + res.getObject(3) + " " + res.getObject(4));
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (res != null)
res.close();
if (sta != null)
sta.close();
if (con != null)
con.close();
}
}
PreparedStatement:
@Test
public void fun2() throws ClassNotFoundException, SQLException{
String driverClassName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mytb";
String username = "root";
String password = "123";
Class.forName(driverClassName);
Connection con = DriverManager.getConnection(url, username, password);
String sql = "select * from emp where ename = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, "甘宁");
ResultSet rs = pstmt.executeQuery();
if(rs.next())
System.out.println(rs.getObject(5));
rs.close();
pstmt.close();
con.close();
}