设计一个程序使用JDBC技术,对MySQL数据库students中的mess表进行增删改操作,并将最终数据库mess的记录内容显示在控制台上(查询操作)。
时间: 2023-03-30 13:01:43 浏览: 77
您好,我可以回答这个问题。以下是使用JDBC技术对MySQL数据库students中的mess表进行增删改操作,并将最终数据库mess的记录内容显示在控制台上的程序示例:
import java.sql.*;
public class JDBCExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/students";
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 = "INSERT INTO mess " +
"VALUES (100, 'John', 'Doe', 'johndoe@example.com')";
stmt.executeUpdate(sql);
//删除操作
sql = "DELETE FROM mess " +
"WHERE id = 101";
stmt.executeUpdate(sql);
//更新操作
sql = "UPDATE mess " +
"SET email = 'newemail@example.com' WHERE id = 102";
stmt.executeUpdate(sql);
//查询操作
sql = "SELECT * FROM mess";
ResultSet rs = stmt.executeQuery(sql);
//显示结果
while(rs.next()){
int id = rs.getInt("id");
String first = rs.getString("first");
String last = rs.getString("last");
String email = rs.getString("email");
System.out.print("ID: " + id);
System.out.print(", First: " + first);
System.out.print(", Last: " + last);
System.out.println(", Email: " + email);
}
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();
}
}
}
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)