JDBC的连接

来源:互联网 发布:ubuntu lamp环境 编辑:程序博客网 时间:2024/05/18 21:07

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);

 

 1JDBC的增删改:

 

Statement sta = con.createStatement();

String sql = "insert into stu values('xiaohong','woman',22,'0010')";

int r = sta.executeUpdate(sql);

 

 2JDBC的查寻:

 

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);

}

 

 3JDBC的关闭:

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();

}

原创粉丝点击