示例代码
将以下示例复制并粘贴到 JDBCExample.java 中,编译并运行如下 -
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
) {
// Execute a query
System.out.println("Inserting records into the table...");
String sql = "INSERT INTO Registration VALUES (100, 'Alex', 'Moo', 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 e) {
e.printStackTrace();
}
}
}
现在让我们编译上面的例子如下 -
C:\>javac JDBCExample.java
C:\>
当你跑 JDBCExample,它产生以下结果 -
C:\>java JDBCExample
Inserting records into the table...
Inserted records into the table...
C:\>