标签:
package com. db.jdbc ;
import java. sql.Connection ;
import java. sql.DriverManager ;
import java. sql.ResultSet ;
import java. sql.SQLException ;
import java. sql.Statement ;
import org. junit.Test ;
public class jdbcTest {
final String url = "jdbc:mysql://localhost:3306/test" ;
final String user = "root";
final String password = "";
ResultSet rs = null;
Statement st = null;
Connection connection = null;
@Test
public void test_jdbc(){
try {
Class .forName( "com.mysql.jdbc.Driver");//加载驱动
connection = DriverManager.getConnection( url, user, password);//获取链接
st = connection. createStatement();//创建执行
rs = st. executeQuery("select
* from test");//执行
while( rs.next ()){//处理结果
System .out. println(rs .getString( "name"));
}
} catch (Exception e) {
e .printStackTrace();
}finally {
try {
if( rs!=null){
rs.close ();
}
if( st!=null){
st.close ();
}
if( connection!=null){
connection.close ();
}
} catch (SQLException e) {
// TODO Auto-generated
catch block
e .printStackTrace();
}
}
}
}
|
测试代码:
@Test
public void test_register_Driver(){
try {
// Class.forName("com.mysql.jdbc.Driver");
// System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver");
DriverManager .registerDriver( new Driver());
Connection connection = DriverManager.getConnection( url, user, password);
Assert .assertEquals( false, connection.isClosed());
} catch (Exception e) {
e .printStackTrace();
}
}
|
@Test
public void test_statement() throws Exception{
Class .forName( "com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection( url, user, password);
Statement st = connection.createStatement ();
ResultSet rs = st.executeQuery ("select
* from test");
while( rs.next ()){
rs .close();
}
ResultSet rs1 = st.executeQuery ("select
* from test");
while( rs1.next ()){
}
}
结果:报错
|
看看statement和 PrparedStatement执行同样的查询
@Test
public void test_statement() throws Exception{
Class .forName( "com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection( url, user, password);
Statement st = connection.createStatement ();
String id = "1";
ResultSet rs = st.executeQuery ("select
* from test where id="+id );
while( rs.next ()){
System .out. println(rs .getString( "name"));
}
}
结果:OK
@Test
public void test_prestatement() throws Exception{
Class .forName( "com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection( url, user, password);
PreparedStatement ps = connection.prepareStatement( "select
* from test where id=?");
ps .setString( 1, "1");
ResultSet rs = ps.executeQuery ();
while( rs.next ()){
System .out. println(rs .getString( "name"));
}
}
结果:OK
|
标签:
原文地址:http://blog.csdn.net/javastudyr/article/details/42596685