Friday, January 19, 2018

Java MySQL INSERT (using Statement)

See also: MySQL XAMPP Connection for Java jdbc Program

First suppose we have a table in out database named user. Or we can create a simple table like below:

create table user (
id int unsigned auto_increment not null,
first_name varchar(25) not null,
last_name varchar(25) not null,
age int not null,
primary key (id)
);
view raw table.sql hosted with ❤ by GitHub


Now we want to insert one record in this table. By following some steps we will do that.
  • Create a Java Connection to our MySQL database.
  • Create a SQL INSERT statement.
  • Then execute a Java Statement, using our SQL INSERT statement.
  • Close our Java MySQL database connection.
  • Finally catch any SQL exceptions using try-catch clause.
package mysqlconn;
import java.sql.*;
import java.util.*;
public class Mysqlconn {
public static void main(String[] args)throws SQLException {
try {
String url="jdbc:mysql://localhost:3306/newdatabase";
Properties prop=new Properties();
prop.setProperty("user","root");
prop.setProperty("password","");
Driver d = new com.mysql.jdbc.Driver();
Connection con = d.connect(url,prop);
if(con == null) {
System.out.println("connection failed");
return;
}
// these are variables to insert
String fname = "Tarek";
String lname = "Ahmed";
int age = 30;
String query1 = "INSERT INTO user(first_name,last_name,age) VALUES('Sifat','Shishir',22);
String query2 = "INSERT INTO user(first_name,last_name,age) VALUES('" + fname + "','" + lname + "','" + age + "')";
Statement state = con.createStatement();
ResultSet result = null;
state.executeUpdate(query1);
state.executeUpdate(query2);
state.close();
} catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}
view raw SQL INSERT.java hosted with ❤ by GitHub


quey1 is passing direct values to the table. query2 is passing values through variables. Be careful about quote marks for executing queries.

See also:
Reference

No comments:

Post a Comment