java的jdbc怎么写
时间: 2023-07-07 07:21:10 浏览: 30
Java JDBC (Java Database Connectivity) 是 Java 用于与关系型数据库进行交互的 API。下面是一个基本的 Java JDBC 示例,可以连接到MySQL数据库并执行查询:
```
import java.sql.*;
public class JdbcExample {
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("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
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();
}
}
System.out.println("Goodbye!");
}
}
```
在运行这个示例之前,需要在 MySQL 中创建一个名为 EMP 的数据库,并向其中添加一个名为 Employees 的表。替换示例中的用户名和密码为您的 MySQL 用户名和密码,并根据您的数据库架构修改 SQL 查询语句。