在java中是如何操作数据库的?
Java中操作数据库通常使用JDBC(Java Database Connectivity)技术,步骤如下:
-
加载数据库驱动:使用
Class.forName(String driver)方法加载数据库驱动。 -
连接数据库:使用
DriverManager.getConnection(String url, String user, String password)方法连接数据库。 -
创建Statement对象:使用connection对象的
createStatement()方法创建Statement对象。 -
执行SQL语句:使用Statement对象的
executeUpdate(String sql)方法执行SQL语句。如果查询语句,使用executeQuery(String sql)方法。 -
处理结果集:对于查询语句,使用ResultSet对象处理结果集。
-
关闭连接:使用connection对象的
close()方法关闭连接。
示例代码:
import java.sql.*;
public class JdbcDemo {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql = "SELECT id, name, age FROM employees";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.print(", Age: " + age);
System.out.println();
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
``
原文地址: https://www.cveoy.top/t/topic/gJFl 著作权归作者所有。请勿转载和采集!