How to insert data into database using Java API? - java

I am trying to insert data into database using the below code but something is not working correctly. It runs without error but it does not insert anything into the database.
public Map<String,String> createuser(String handle, String password, String fullname, String location, String xmail, String bdate)
{
Map<String,String> userIdMap = new HashMap<>();
PreparedStatement stmt = null;
try
{
Connection conn = ds.getConnection();
String queryString = null;
queryString = "INSERT INTO Identity(handle, password, fullname, location, xmail, bdate) VALUES (?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(queryString);
stmt.setString(1, handle);
stmt.setString(2, password);
stmt.setString(3, fullname);
stmt.setString(4, location);
stmt.setString(5, xmail);
stmt.setString(6, bdate);
userIdMap.put(handle, password);
userIdMap.put(fullname, location);
userIdMap.put(xmail, bdate);
int s = stmt.executeUpdate(queryString);
stmt.close();
conn.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
return userIdMap;
} // createuser()
Possible error message
<html><head><title>Grizzly 2.3.23</title><style><!--div.header {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#003300;font-size:22px;-moz-border-radius-topleft: 10px;border-top-left-radius: 10px;-moz-border-radius-topright: 10px;border-top-right-radius: 10px;padding-left: 5px}div.body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:#FFFFCC;font-size:16px;padding-top:10px;padding-bottom:10px;padding-left:10px}div.footer {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#666633;font-size:14px;-moz-border-radius-bottomleft: 10px;border-bottom-left-radius: 10px;-moz-border-radius-bottomright: 10px;border-bottom-right-radius: 10px;padding-left: 5px}BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;}B {font-family:Tahoma,Arial,sans-serif;color:black;}A {color : black;}HR {color : #999966;}--></style> </head><body><div class="header">Request failed.</div><div class="body">Request failed.</div><div class="footer">Grizzly 2.3.23</div></body></html>

Instead of having us follow you on a journey to go find where your stack trace is getting logged, just add this into your catch block. This is going to be the fastest path right now to actually showing you your error message.
} catch (SQLException e) {
System.out.format("SQL State: %s\n%s\n", e.getSQLState(), e.getMessage());
...
...
}

Related

If I execute my query through phpMyAdmin it works while it doesn't in my java program

I'm new to java and for an exam, I have to make an app that's a store for a book shop but I'm having problems with the database part of the app: my prepared statement isn't working while if I copy the query generated from it and paste it into phpMyAdmin it works perfectly.
The error the app is giving me is:
java.sql.SQLSyntaxErrorException: You have an error in your SQL
syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near 'SET #address =
LAST_INSERT_ID(); INSERT INTO utenti (email, password, nome, cogn' at
line 1
The method that generates the error
public static void createUser(String email, String password, String nome, String cognome, long telefono, String indirizzo, int cap, String città) throws Exception{
Connection conn = MysqlConnection.getConnection();
try{
st = conn.prepareStatement("INSERT INTO indirizzi (indirizzo, cap, città) "
+ "VALUES (?,?,?); "
+ "SET #address = LAST_INSERT_ID(); "
+ "INSERT INTO utenti (email, password, nome, cognome, telefono, idindirizzo) "
+ "VALUES (?, ?, ?, ?, ?, #address);");
st.setString(1, indirizzo);
st.setInt(2, cap);
st.setString(3, città);
st.setString(4, email);
st.setString(5, password);
st.setString(6, nome);
st.setString(7, cognome);
st.setLong(8, telefono);
System.out.println(st);
st.executeUpdate();
}
catch(Exception e){
throw e;
}
finally{
try{
conn.close();
}
catch(SQLException e){
throw e;
}
}
}
The method where it's used (just a test method to see if the other one works)
private static void createUser()
{
try {
ModelUser.createUser("a#a.com", "qwertyasdfg", "Aldo", "Simone", 391234567890l, "via dietro 1/g", 37051, "Sì");
} catch (Exception e) {
e.printStackTrace();
}
}
The generated sql
INSERT INTO indirizzi (indirizzo, cap, città) VALUES ('via dietro 1/g',37051,'Sì'); SET #address = LAST_INSERT_ID(); INSERT INTO utenti (email, password, nome, cognome, telefono, idindirizzo) VALUES ('a#a.com', 'qwertyasdfg', 'Aldo', 'Simone', 391234567890, #address);
A little edited for readability
INSERT INTO indirizzi (indirizzo, cap, città)
VALUES ('via dietro 1/g',37051,'Sì');
SET #address = LAST_INSERT_ID();
INSERT INTO utenti (email, password, nome, cognome, telefono, idindirizzo)
VALUES ('a#a.com', 'qwertyasdfg', 'Aldo', 'Simone', 391234567890, #address);
I think that this should be working since the query itself is working when it's put into phpMyAdmin
You are actually trying to execute two queries with one prepared statement. change your method like following
public static void createUser(String email, String password,
String nome, String cognome, long telefono, String indirizzo,
int cap, String città) throws Exception{
Connection conn = MysqlConnection.getConnection();
try{
PreparedStatement st = conn.prepareStatement("INSERT INTO indirizzi
(indirizzo, cap, città) VALUES (?,?,?)");
st.setString(1, indirizzo);
st.setInt(2, cap);
st.setString(3, città);
st.executeUpdate();
/* You may want to close PreparedStatement here */
st = conn.prepareStatement("INSERT INTO utenti
(email, password, nome, cognome, telefono, idindirizzo)
VALUES (?, ?, ?, ?, ?, LAST_INSERT_ID())");
st.setString(1, email);
st.setString(2, password);
st.setString(3, nome);
st.setString(4, cognome);
st.setLong(5, telefono);
st.executeUpdate();
/* You may want to close PreparedStatement here */
}catch(Exception e){
throw e;
}finally{
try{
conn.close();
}
catch(SQLException e){
throw e;
}
}
}

Getting Java mysql SQL Syntax error but my query seems normal

I am developing a simple java mysql based application and during data insertion into the database I'm getting an SQL error mentioned below.
Here is my code:
public DBConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase?useUnicode=true&useLegacyDatetimeCode=false&serverTimezone=Turkey", "root", "");
st = con.createStatement();
System.out.println("CONNECTED!");
} catch (Exception e) {
System.out.println("Error : " + e);
}
}
public void addCustomer(String name, String surname, String company, String adress, String adressTwo){
String addQuery = "insert into musteri (name,surname,company,adress,adressTwo) values (?,?,?,?,?)" ;
try {
st.executeUpdate(addQuery);
System.out.println("Data Added");
} catch (Exception e) {
System.out.println("Error occured when adding value to database : " + e );
}
}
Here is my java main method that add's the data:
public static void main(String[] args) {
// TODO code application logic here
Customers c1 = new Customers();
c1.setIsim("test");
c1.setSoyisim("test");
c1.setSirket("test");
c1.setAdres("test");
c1.setIletisim("test");
DBConnection db = new DBConnection();
db.addCustomer(c1.isim, c1.soyisim, c1.sirket, c1.adres, c1.iletisim);
}
The error I'm getting is:
Error occured when adding value to database : java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''insert into musteri (ad,soyad,sirket,adres,iletisim) values (?,?,?,?,?)'' at line 1
You are mixing statements with prepared statements. You should use a prepared statement and set the values to it:
public void addCustomer(String name, String surname, String company, String address, String adressTwo) {
String addQuery = "insert into musteri (name, surname, company, adress, adressTwo) values (?,?,?,?,?)" ;
// Shown here for simplicitly.
// The query could be prepared once and stored in a data member
try (PreparedStatement ps = con.prepareStatement(addQuery)) {
ps.setString(1, name);
ps.setString(2, surname);
ps.setString(3, company);
ps.setString(4, address);
ps.setString(5, addressTwo);
ps.executeUpdate();
System.out.println("Data Added");
} catch (Exception e) {
System.out.println("Error occured when adding value to database : " + e );
}
}
May I suggest you implement addCustomer like this. Use a local Statement and create it by using try-with-resource style and then set your parameters for the query
public void addCustomer(String name, String surname, String company, String adress, String adressTwo){
String addQuery = "insert into musteri (name,surname,company,adress,adressTwo) values (?,?,?,?,?)" ;
try (PreparedStatement stmt = con.prepareStatement(addQuery)) {
stmt.setString(1, name);
stmt.setString(2, surname);
stmt.setString(3, company);
stmt.setString(4, adress);
stmt.setString(5, adressTwo);
stmt.executeUpdate();
System.out.println("Data Added");
} catch (Exception e) {
System.out.println("Error occured when adding value to database : " + e );
}
}

connecting javaprogram to mysql database

String dburl = "jdbc:mysql://localhost:3306/librarymanagementsystem";
String user = "nandika";
String password = "nandika";
public void createConnection(int id, String name, String author, String
publisher) {
try {
Connection mycon = DriverManager.getConnection(dburl);
Statement mystmt = mycon.createStatement();
String sql = "insert into addbook" + "(Book ID,Book
Name,Author,Publisher)" + "values" + "(" + id + "," + name + "," +
author + "," + publisher + ")";
mystmt.executeUpdate(sql);
System.out.println("updated");
} catch (Exception ex) {
}
execute update is a method in another class.there seem to be
whats the wrong with this code segment? database is not updating!!
You have not loaded the database drivers, to do that include this code:
Class.forName("com.mysql.jdbc.Driver");
If you haven't drivers download and put in project library.
Their are some problems with this code snippet. One is you didn't load the database. Also you didn't use the username and password.
I recommend you to create the database connection separately. Maybe in a separate Java file. As below,
public class DatabaseConnection {
public static Statement getConnection() throws Exception{
Class.forName("com.mysql.jdbc.Driver"); //Loading the database
Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3307/restaurentsystem","nandika","nandika"); //username and password can save as variables and pass here
Statement statement = c.createStatement();
return statement;
}
}
Then you can use it whenever you want. In this situation,
try {
Statement s = DatabaseConnection.getConnection();
s.executeUpdate("INSERT INTO addbook (Book ID, Book Name, Author, Publisher) VALUES (?, ?, ?, ?);"); //Values should assign here.
System.out.println("updated");
} catch (Exception e) {
System.out.println(e);
}
This is what I do if I do this. I recommend you to try this method.
This is the way you should be doing it, with preparedStatement to prevent injections
String dburl = "jdbc:mysql://localhost:3306/librarymanagementsystem";
String user = "nandika";
String password = "nandika";
private PreparedStatement preparedStatement;
private Connection con = null;
public static void main(String[] args) {
}
public void createConnection(int id, String name, String author, String publisher) {
try {
con = DriverManager.getConnection(dburl, user, password);
String stmt = "INSERT INTO addbook (Book ID,Book Name,Author,Publisher) VALUES (?, ?, ?, ?)";
preparedStatement = con.prepareStatement(stmt);
preparedStatement.setInt(1, id);
preparedStatement.setString(2, name);
preparedStatement.setString(3, author);
preparedStatement.setString(4, publisher);
preparedStatement.executeUpdate();
con.close();
System.out.println("updated");
} catch (Exception ex) {
}

Insert data to MS Access DB through JDBC-ODBC

I tried to insert some data from java to my database (ms.access) but when I click button nothing add to database. here is the code:
private void EmpButtonMouseClicked(java.awt.event.MouseEvent evt) {
String name,sex,email,username,password;
name = tfName.getText();
sex=(String) cbSex.getSelectedItem();
email=tfEmail.getText();
username=tfUser.getText();
try{
String url;
url = "jdbc:odbc:mydata";
Connection conn = DriverManager.getConnection(url,"","");
Statement stm = conn.createStatement();
stm.executeUpdate("INSERT INTO EmployeeLogin " + "VALUES (name, email, sex, username)");
conn.close();
}catch (SQLException sqlException){}
}
what wrong with that code?
I think I found the way to do it...
String sex=(String) cbSex.getSelectedItem();
try{
String url = "jdbc:odbc:mydata";
Connection conn = DriverManager.getConnection(url,"","");
String sql = "INSERT INTO CustomerLogin(Name, Email, Sex, Username, Password) VALUES(?,?,?,?,?)";
pst=conn.prepareStatement(sql);
pst.setString(1, tfName.getText());
pst.setString(2, tfEmail.getText());
pst.setString(3, sex);
pst.setString(4, tfUser.getText());
pst.setString(5, pfPassword.getText());
pst.execute();
tfName.setText("");
tfEmail.setText("");
tfUser.setText("");
pfPassword.setText("");
JOptionPane.showMessageDialog(null,"Succed Create Account! You can now return to Login Page");
}catch (Exception e){
JOptionPane.showMessageDialog(null,e); }
The Problem is :
stm.executeUpdate("INSERT INTO EmployeeLogin " + "VALUES (name, email, sex, username)");
write like :
stm.executeUpdate("INSERT INTO EmployeeLogin VALUES ("+name+", "+email+", "+sex+", "+username+")");

Null pointer exception on insert into database java

Hi I have this method below which should insert values into my database. However I am getting a Null Pointer Exception on the PreparedStatement line
public void insertReservation(String name, String phone, int size, String date, String time, String additionalRequirements, String memberID, String themeID) throws SQLException, ClassNotFoundException {
try {
String strQuery = "INSERT INTO reservation VALUES (?, ? ,?, TO_DATE(?, 'dd-MMM-yy'), ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(strQuery);/
stmt.setString(1, name);
stmt.setString(2, phone);
stmt.setInt(3, size);
stmt.setString(4, date);
stmt.setString(5, time);
stmt.setString(6, additionalRequirements);
stmt.setString(7, memberID);
stmt.setString(8, themeID);
results = stmt.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}//end try
}
Am I inserting this correctly into my database? I am not sure why I am getting this null pointer exeception error.
conn is null, print its value.
Don't know but try this
String strQuery = "insert into reservation(ColumnName1, ColumnName2 ,ColumnName3,) values(?,?,?)";
and at the end it will be only execute();
like this stmt.execute();
executeQuery(); statement works with select query Only
Secondly have you described conn value in constructor or method in which ever class you are using the query if you have than assign it like this conn= SqlConnection.ConnecrDb();
below is the SqlConnection Seperate class i have created
public class SqlConnection {
Connection conn=null;
public static Connection ConnecrDb(){
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn= DriverManager.getConnection("jdbc:odbc:Test","","");
return conn;
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
Hope it will help you

Categories