How does Java work with a MySQL database to insert data?

1. Create a database:

Create a database using the statement below:

mysql> create database hitech;

2. Create a database Table:

In this instance, I’m using the JAVA programming language to add records to a MySQL database. In MySQL, a table must first be created. As follows is the question:

mysql> create table Insert

   -> (

   -> Id int,

   -> Name varchar(200),

   -> Age int

   -> );

Query OK, 0 rows affected (0.97 sec)

The steps following should be followed in order to insert a Data into a MySQL database:

The DriverManager class’s getConnection() method allows you to establish a database connection.

By providing the login, password, and MySQL URL, which is jdbc:mysql:/localhost/hitech (where hitech is the database name), as inputs to the getConnection() method, you can connect to the MySQL database.

String mysqlUrl = “jdbc:mysql://localhost/hitech”;

Connection con = DriverManager.getConnection(mysqlUrl, “root”, “password”);

3. Create a prepared statement in step two:

PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?, ?)");

4. Execute the statement in step Three:

//Sample code
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
public class JavaInsertDemo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
try {
Class.forName(“com.mysql.jdbc.Driver”);
} catch (Exception e) {
System.out.println(e);
}
String mysqlUrl = “jdbc:mysql://localhost/hitech”;
Connection con = DriverManager.getConnection(mysqlUrl, “root”, “password”);
System.out.println(“Connection is created successfully:”);
stmt = (Statement) con.createStatement();
String query1 = “INSERT INTO Insert ” + “VALUES (1, ‘John’, 34)”;
stmt.executeUpdate(query1);
query1 = “INSERT INTO Insert ” + “VALUES (2, ‘Carol’, 42)”;
stmt.executeUpdate(query1);
System.out.println(“Record is inserted in the table successfully………………”);
} catch (SQLException excep) {
excep.printStackTrace();
} catch (Exception excep) {
excep.printStackTrace();
} finally {
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println(“Please check it in the MySQL Table……… ……..”);
}
}

Output

Connection established……
Record inserted……

Use the SELECT statement to determine whether a record has been added into a table. The issue is as follows:
mysql> select *from Insert;

Here is the output −
+------+-------+------+
| Id   | Name  | Age  |
+------+-------+------+
|    1 | John  |   34 |
|    2 | Carol |   42 |
+------+-------+------+
2 rows in set (0.00 sec)

 

Leave a Comment

Your email address will not be published. Required fields are marked *