代碼如下:
import java.sql.*;
public class jdbc {
@SuppressWarnings("unused")
public static void main(String[] args) {
// TODO Auto-generated method stub
JdbcConnection jdbcConnection = new JdbcConnection();
}
}
//定義一個連接配接類
class JdbcConnection
{
//建立一個用于連接配接的對象
Connection ct = null;
//建立一個用于發送sql語句的對象
PreparedStatement ps = null;
//建立一個用于接收結果集的對象
ResultSet rs = null;
//預設構造函數
public JdbcConnection()
{
try {
//加載驅動
Class.forName("org.gjt.mm.mysql.Driver");
//得到連接配接
ct = DriverManager.getConnection
("jdbc:mysql://46.77.201.185:3306/SMOS?user=root&password=wtuliumeng&useUnicod e=true&characterEncoding=8859_1" );
//查詢
ps = ct.prepareStatement("select * from student");
//得到結果
rs = ps.executeQuery();
//循環輸出
while(rs.next())
{
String a = rs.getString(1);
String b = rs.getString(2);
System.out.println(a + " " + b);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally
{
try {
//關閉資源
if(rs != null)
{
rs.close();
}
if(ps != null)
{
ps.close();
}
if(ct != null)
{
ct.close();
}
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}