代码如下:
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();
}
}
}
}