黑马程序员技术交流社区
标题:
数据库的连接与查询
[打印本页]
作者:
huangxuanheng
时间:
2014-9-4 12:33
标题:
数据库的连接与查询
<P>
<P>package com.mysql;
/**</P>
<P>一个简单的mysql数据库连接和查询,本人创建的数据库名是student,student中有一张数据表info</P>
<P> </P>
<P>*/
import java.sql.*;
public class MysqlConnection {</P>
<P>//数据库连接接口,用于连接特定的数据库
Connection connection;</P>
<P>//prepare为获取数据库执行语句
PreparedStatement prepare;</P>
<P>//rs对象实现对数据库的查询
ResultSet rs;</P>
<P>//数据库驱动类
String driver="com.mysql.jdbc.Driver";</P>
<P>//数据库的URL
String url="jdbc:mysql://localhost:3306/student";</P>
<P>//数据库的用户名
String username="root";</P>
<P>//用户名的密码
String password="huangxuanheng";
/**</P>
<P>该方法创建了数据库连接对象,返回该连接对象</P>
<P>*/
public Connection getConnection(){
try {</P>
<P>//加载数据库驱动类
Class.forName(driver);</P>
<P>//访问数据库连接对象
connection=DriverManager.getConnection(url,username,password);
} catch (Exception e) {
// TODO: handle exception
}
return connection;
}</P>
<P>/**</P>
<P>构造方法中封装了一个简单的查询</P>
<P>*/
public MysqlConnection(){
try {
prepare=getConnection().prepareStatement("select * from info");
rs=prepare.executeQuery();
while(rs.next()){
String id=rs.getString(1);
String name=rs.getString(2);
System.out.println(id+name);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(prepare!=null){
try {
prepare.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new MysqlConnection();
}
}</P>
<P> </P></P>
复制代码
运行结果如下:
3huangxuanheng
6sunwukong
10zhubajie
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2