Develop a Java program to demonstrate the execution of create and insertqueries using JDBC
Question
Develop a Java program to demonstrate the execution of create and insert queries using JDBC
Solution
Sure, here is a simple Java program that demonstrates the execution of create and insert queries using JDBC.
import java.sql.*;
public class Main {
public static void main(String[] args) {
try {
// Step 1: Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Step 2: Establish a connection to the database
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase", "username", "password");
// Step 3: Create a statement
Statement stmt = conn.createStatement();
// Step 4: Execute a create query
String createQuery = "CREATE TABLE Students (ID INT, Name VARCHAR(20), Age INT, Gender CHAR(1))";
stmt.executeUpdate(createQuery);
// Step 5: Execute an insert query
String insertQuery = "INSERT INTO Students VALUES (1, 'John Doe', 20, 'M')";
stmt.executeUpdate(insertQuery);
// Step 6: Close the connection
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Please replace "com.mysql.jdbc.Driver"
, "jdbc:mysql://localhost:3306/myDatabase"
, "username"
, and "password"
with your actual JDBC driver, database URL, username, and password.
This program does the following:
- Loads the JDBC driver.
- Establishes a connection to the database.
- Creates a
Statement
object. - Executes a
CREATE TABLE
query to create a new table namedStudents
. - Executes an
INSERT INTO
query to insert a new row into theStudents
table. - Closes the connection to the database.
Please note that this is a very basic example and doesn't include any error handling or transaction management code that a real-world application should have.
Similar Questions
What are the basic steps for JDBC connection, explain it with suitable program. give me the content for 5 marks
In Java, which method is commonly used for executing SQL queries in JDBC?Question 1Answera.executeQuery()b.executeUpdate()c.execute()d.runQuery()
Which package in Java provides the necessary classes and interfaces for JDBC?Question 5Answera.java.sqlb.java.dbc.javax.jdbcd.jdbc.connection
Which of the following is not a valid statement in JDBC?Question 11Answera.Statementb.PreparedStatementc.QueryStatementd.CallableStatement
How is a connection to a database established in JDBC?Question 6Answera.Using ConnectionFactoryb.Through DriverManagerc.Using SQLConnectiond.Through DataSource
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.