public void fun3() throws SQLException
{
Connection connection=null;
Statement statement=null;
ResultSet resultSet=null;
try{
String driverClassName="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/exam";
String username="root";
String password="123";
Class.forName(driverClassName);
connection=DriverManager.getConnection(url,username,password);
/*
* 创建statement
*/
statement=connection.createStatement();
String sqlString="select * from emp";
resultSet=statement.executeQuery(sqlString);
/*
*
* 循环遍历rs ,打印其中数据
*/
while(resultSet.next())
{
System.out.println(resultSet.getString(1)+","+resultSet.getString(2));
}
}catch(Exception e)
{
throw new RuntimeException(e);
}
finally{
//关闭资源
if(resultSet!=null) resultSet.close();
if(statement!=null) statement.close();
if(connection!=null) connection.close();
}
}
1.定义数据库协议,定义用户名,密码
2.加载驱动
3.获得connection连接
4.创建statement对象
5.准备sql
6.执行sql
7.关闭资源
网友评论