您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

JDBC 插入记录

JDBC 插入记录

本章提供了有关如何使用JDBC应用程序在表中插入记录的示例。在执行以下示例之前,请确保已具备以下条件:

  • 要执行以下示例,您可以将用户名密码替换为实际的用户名和密码。

  • 您的MySQL或您使用的任何数据库均已启动并正在运行。

必要步骤

使用JDBC应用程序创建新数据库需要执行以下步骤-

  • 导入包:要求您包含包含数据库编程所需的JDBC类的软件包。通常,使用 import java.sql.* 就足够了。

  • 注册 JDBC 驱动程序: 要求您初始化驱动程序,以便您可以打开与数据库的通信通道。

  • 建立连接:需要使用 DriverManager.getConnection() 方法来创建一个Connection对象,该对象表示与数据库服务器的物理连接。

  • 执行查询: 需要使用Statement类型的对象来构建和提交SQL语句,以便在选定的数据库中创建表。

  • 清理环境: 需要显式关闭所有数据库资源,而不是依赖JVM的垃圾回收。

示例代码

将以下示例复制并粘贴到JDBCExample.java中,编译并运行如下-

//步骤1.导入所需的软件包
import java.sql.*;

public class JDBCExample {
   // JDBC驱动程序名称和数据库URL
   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{
      //步骤2:注册JDBC驱动程序
      Class.forName("com.mysql.jdbc.Driver");

      //步骤3:建立连接
      System.out.println("Connecting to a selected database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      System.out.println("Connected database successfully...");
      
      //步骤4:执行查询
      System.out.println("Inserting records into the table...");
      stmt = conn.createStatement();
      
      String sql = "INSERT INTO Registration " +
                   "VALUES (100, 'Zara', 'Ali', 18)";
      stmt.executeUpdate(sql);
      sql = "INSERT INTO Registration " +
                   "VALUES (101, 'Mahnaz', 'Fatma', 25)";
      stmt.executeUpdate(sql);
      sql = "INSERT INTO Registration " +
                   "VALUES (102, 'Zaid', 'Khan', 30)";
      stmt.executeUpdate(sql);
      sql = "INSERT INTO Registration " +
                   "VALUES(103, 'Sumit', 'Mittal', 28)";
      stmt.executeUpdate(sql);
      System.out.println("Inserted records into the table...");

   }catch(SQLException se){
      //处理JDBC错误
      se.printStackTrace();
   }catch(Exception e){
      //处理Class.forName的错误
      e.printStackTrace();
   }finally{
      //用于关闭资源
      try{
         if(stmt!=null)
            conn.close();
      }catch(SQLException se){
      }// 没做什么
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }
   }//结束try
   System.out.println("Goodbye!");
}//结束main
}//结束JDBCExample

现在,让我们编译上面的示例,如下所示:

C:\>javac JDBCExample.java
C:\>

运行时JDBCExample,它将产生以下结果-

C:\>java JDBCExample
Connecting to a selected database...
Connected database successfully...
Inserting records into the table...
Inserted records into the table...
Goodbye!
C:\>

联系我
置顶