Null pointer exception on insert into database java - 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

Related

How to insert data into database using Java API?

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());
...
...
}

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 );
}
}

how to set local variable for transaction in jdbc

I'm working on a project in whose database I need to initialize a session variable. If I work directly with sql, the initialization is done with SET statement
set local app.user_id to "0000";
I try to initialize it with Connection#setClientInfo() but failed
try(Connection connection = getDataSource().getConnection()) {
boolean isAutoCommit = connection.getAutoCommit();
try {
Properties properties = new Properties();
properties.put("app.user_id", "0000");
connection.setAutoCommit(false);
connection.setClientInfo(properties);
String query = "insert into positions (name, description) values (?, ?)";
try(PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, position.getName());
statement.setString(2, position.getDescription());
statement.executeUpdate();
}
connection.commit();
}
catch (SQLException e) {
e.printStackTrace();
connection.rollback();
}
finally {
connection.setAutoCommit(isAutoCommit);
}
}
I get PSQLException (insert query is dependent on parameter and it does not pass)
org.postgresql.util.PSQLException: ERROR: unrecognized configuration parameter "app.user_id"
If I use PreparedStatement I get PSQLException with message ERROR: syntax error at or near "$1"
try(Connection connection = getDataSource().getConnection()) {
boolean isAutoCommit = connection.getAutoCommit();
try {
connection.setAutoCommit(false);
try(PreparedStatement statement = connection.prepareStatement("set local app.user_id to ?")) {
statement.setString(1, "0000");
statement.execute();
}
String query = "insert into positions (name, description) values (?, ?)";
try(PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, position.getName());
statement.setString(2, position.getDescription());
statement.executeUpdate();
}
connection.commit();
}
catch (SQLException e) {
e.printStackTrace();
connection.rollback();
}
finally {
connection.setAutoCommit(isAutoCommit);
}
}
The only way to go through is by directly executing the query with fixed values. But in doing so, I am forced to use a concatenation to build the query. And I do not want to do it.
try(Connection connection = getDataSource().getConnection()) {
boolean isAutoCommit = connection.getAutoCommit();
try {
connection.setAutoCommit(false);
try(Statement statement = connection.createStatement()) {
statement.execute("set local app.user_id to 0000");
}
String query = "insert into positions (name, description) values (?, ?)";
try(PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, position.getName());
statement.setString(2, position.getDescription());
statement.executeUpdate();
}
connection.commit();
}
catch (SQLException e) {
e.printStackTrace();
connection.rollback();
}
finally {
connection.setAutoCommit(isAutoCommit);
}
}
What is the right way to initialize such parameters?
I use PostgreSQL 11, JDBC 4.2 (with driver 42.2.5) and DBCP 2.5
Edit
I did it by calling set_config.
try(PreparedStatement statement = connection.prepareStatement("select set_config(?, ?, true)")) {
statement.setString(1, "app.user_id");
statement.setString(2, "0000");
statement.execute();
}
But the question remains. How to call SET in JDBC
I think you need to do this on the DataSource not the Connection.
In postgresql the only way I know of would be to downconvert. Something like:
DataSource myDS = getDataSource();
if (DataSource instanceof BaseDataSource.class) {
BaseDataSource pgDS = (BaseDataSource) myDS; // expose setProperty method
pgDS.setProperty("app.user_id", "0000");
}
where you place this in your application obviously depends upon many details not presented in your question.

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) {
}

Running executeBatch() from another location

I want to create another method called public void execute() and run the preparedStmt.executeBatch(); from there, but I don't know how.
public void save() {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Sacuvano nov proizvod sa sifrom: " + proizvodID + " Naziv proizvoda: " + naziv));
try {
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/fpis";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "root");
String query = " insert into proizvod values (?, ?, ?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, proizvodID);
preparedStmt.setString(2, naziv);
preparedStmt.setString(3, opis);
preparedStmt.setDouble(4, cena);
preparedStmt.setString(5, jedMere);
preparedStmt.addBatch();
preparedStmt.executeBatch();
conn.close();
} catch (Exception e) {
System.err.println("Greska!");
System.err.println(e.getMessage());
}
}
public void execute(){
{
You should declare PreparedStatement preparedStmt and Connection conn as a attribute of your class.
Like that you could setup preparedStmt in public void save() and conn in your constructor. After that, just call preparedStmt.executeBatch(); from public void execute(); and close conn after.

Categories