You can follow the steps shown below to create a table in your database server. In our case, the database name is library and the table name is books. The SQL query to create this table is shown below.
You may try the following code to insert book information into the book table.
package com.t4b.jdbc.mysql.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TestMain {
static {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
String name = "PHP";
String author = "John";
String publisher = "Oxf";
Connection con = null;
Statement stmt = null;
try {
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/library", "root", "iltwat");
stmt = con.createStatement();
stmt.executeUpdate("insert into books values ('" + name + "', '" + author + "', '" + publisher + "')");
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.