JDBC --- Java DataBase Connectivity / Java数据库链接
通过JDBC访问数据库一般有以下几步:
1)加载JDBC驱动器。
将 mysql-connector-java-5.1.32-bin.jar 包放入WEB-INF/lib目录下
2)加载JDBC驱动,将目标注册到DriverManager中。一般使用反射机制class.forName(String driver);
3)建立数据库连接,取得Connection对象。一般是DriverManager.getConnection(url,user,password);
4)建立PreparedStatement对象或者是Statement对象。
5)执行SQL语句。
6)访问结果集ResultSet对象。
7)关闭资源,依次是:ResultSet、PreparedStatement、Connection
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestJDBC {
public static void main(String[] args) {
String user="root";
String password="root";
String url="jdbc:mysql://localhost:3306/friend";
String driver="com.mysql.jdbc.Driver";
Connection connection=null;
PreparedStatement pst=null;
ResultSet rs=null;
try {
Class.forName(driver);
connection=DriverManager.getConnection(url,user,password);
String sql="select idfriend,username from friend where idfriend= ? ";
pst=connection.prepareStatement(sql);
pst.setInt(1, 2);
rs=pst.executeQuery();
while (rs.next()) {
int d=rs.getInt("idfriend");
String name =rs.getString("username");
System.out.println(d+"--------"+name);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if (rs!=null)
rs.close();
if (pst!=null)
pst.close();
if (connection!=null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}