Recently I'm just learning some HTML, JSP and servlets for a university project, the thing is that I made a database into MySQL Workbench with id primary key, auto increment , then some fields like username, password, firstname, lastname, and so on.
The goal is to make a login page and register page, for some reason if I push data with MySQL Workbench into the database it will let me retrieve it with my login form and my select statment, but for some reason I'm doing the same thing with register but in this case with the query INSERT.
So, after research, I did preparestatment and changed the executeQuery to executeUpdate and everything, but my log says a nullPointerException somewhere, I know it may be a simple and silly error that I'm not seeing, but I'm new at this. This is what U have made so far to insert data into my database:
public static UserBean registarUsuario(UserBean bean){
//preparing some objects for connection
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
System.out.println("Error al cargar el driver");
System.out.println(ex.getMessage());
}
String firstname = bean.getFirstName();
String lastname = bean.getLastName();
String username = bean.getUsername();
String password = bean.getPassword();
boolean admin = bean.isAdmin();
int tipo = bean.getType();
String insertQuery =
"insert into idusuario (firstname,lastname,username,password,admin,tipo) values ('"+firstname+"','"+lastname+"','"+username+"','"+password+"','"+admin+"','"+tipo+"')";
System.out.println("Firstname is " + firstname);
System.out.println("Surname is " + lastname);
System.out.println("Query: "+insertQuery);
try
{
//connect to DB
currentCon = DriverManager.getConnection("jdbc:mysql://localhost:3306/usuarios", "root", "admin");
rs = stmt.executeQuery(insertQuery);
...
My output:
Info: Query: insert into idusuario
(firstname,lastname,username,password,admin,tipo) values
('jhon','marston','jmar','123','true','0') Info: Error :
java.lang.NullPointerException
The thing is that Netbeans doesn't even tell me where the NPE is happening so I'm kind of confused, I don't know if the query is wrong or if something else is, because as I can see in my output, the query seems ok.
I leave you here my database structure
You are assigining the stmt as null and never initializing it.
Statement stmt = null;
ResultSet rs = null;
Then you are trying to use it:
rs = stmt.executeQuery(insertQuery);
You will need to do something like this before you use it:
PreparedStatement stmt=currentCon.prepareStatement(yourQuery);
So, after research, i did preparestatment and changed the executeQuery
to executeUpdate and everything, but my log says a
nullPointerException somewhere, i know it may be a simple and silly
error that im not seeing, but understand that im new at this. this is
what i have made so far to insert data into my database
When we use insert,update or delete we need to use executeUpdate.
When we use select we need to use executeQuery.
In your example you are doing executeQuery for an insert. This is wrong. You need to use this:
rs = stmt.executeUpdate(insertQuery);
You're getting a NPE because you are trying to retrieve the results where there are none.
Here is a nice thing to do to help you reduce boilerplate code... (so you don't have to keep repeating yourself with db initialization values)
Create a class for your database connection:
public class DBConnection {
private static String url = null;
private static Connection conn = null;
public static Connection getConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://localhost:3306/usuarios";
conn = DriverManager.getConnection(url,"root","admin");
} catch (Exception e) {
System.out.println(e);
}
return conn;
}
}
Now you can use this in all your other classes like this:
public static UserBean registarUsuario(UserBean bean){
try(Connection conn= DBConnection.getConnection()){
PreparedStatement pst = conn.prepareStatement("insert into idusuario (firstname,lastname,username,password,admin,tipo) values (?,?,?,?,?,?);");
pst.setString(1, bean.getFirstName());
pst.setString(2, bean.getLastName());
pst.setString(3, bean.getUserName());
pst.setString(4, bean.getPassword());
pst.setBoolean(5, bean.isAdmin());
pst.setInt(6, bean.getType());
pst.executeUpdate();
}catch (SQLException e) {
e.printStackTrace();
}
}
Hello i need to do 2 active jobs with database in java.Firstly I did with 1 statement but after I read hints in here they said that I should use 2 statement.But although it still get Operation not allowed after ResultSet closed error.
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e){
System.err.println("Driver yok");
return;
}
Connection con=null;
try{
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/kutuphane","root","");
System.out.println("Veritabnı baglandıldı");
Statement stmt=con.createStatement();
String strSQL="UPDATE emanetler SET IADETARIH='"+strdate+"' WHERE KISIAD='"+jTextField1.getText()+"' "
Statement stmt2=con.createStatement();
stmt.execute(strSQL);
ResultSet rs=stmt2.executeQuery("SELECT * FROM kitaplar");
while(rs.next()){
if(rs.getString("KITAPAD").equals(jTextField2.getText())){
strSQL="UPDATE kitaplar SET KITAPADET="+rs.getInt("KITAPADET")+"+1 WHERE KITAPAD='"+jTextField2.getText()+"' ";
stmt2.execute(strSQL);
}
}
stmt.close();
stmt2.close();
}
catch(SQLException e){
System.out.println("Veritabanı baglanmadi");
e.printStackTrace();
}
First you are using stmt2 object
ResultSet rs=stmt2.executeQuery("SELECT * FROM kitaplar");
Then in while loop
strSQL="UPDATE kitaplar SET KITAPADET="+rs.getInt("KITAPADET")+"+1 WHERE KITAPAD='"+jTextField2.getText()+"' ";
stmt2.execute(strSQL);
This must be corrected to use a separate Statement Object in While Loop to execute queries.
Hope this helps
I am playing with HSQLDB+JDBC driver using JDK 8.
Using rs.next() looping results works fine, however, using rs.first() does not work: feature is not supported ?! Is is by design or a bug?
I plan to access hsqldb using Spring jdbc template, and I am concerned that I may stuck if I encounter such issue later on.
String jdbcUrl = "jdbc:hsqldb:hsql://localhost:9999/configdb";
try(Connection con = DriverManager.getConnection(jdbcUrl, "SA", "");
PreparedStatement stmt = con.prepareStatement(
"SELECT * FROM contacts");
) {
ResultSet rs = stmt.executeQuery();
// rs.first() does not work !
while(rs.next()){
//do sth here
}
} catch (SQLException e) {
throw new RuntimeException("test jdbc connection failed", e);
}
Try to make your ResultSet scrollable:
PreparedStatement stmt= conn.prepareStatement("SELECT * FROM contacts",
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
I think that should probably work
I have MySQL database "database" in my web. I want to connect it remotly from java. But I get Exception.
I use this code to connect it.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://site.ir:3306/database", username", "password");
Statement st = con.createStatement();
String sql = ("SELECT * FROM users ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
int id = rs.getInt("id");
String str1 = rs.getString("imei");
System.out.print(id+"+++"+str1);
}
con.close();
}catch(Exception e){
e.printStackTrace();
}
I think there's no problem in my code and username has All permission to access database! Please say what's problem!
Here is the preparatory statement I am using after making jdbc connection (Using SQL Developer) but on execution I am getting the following error
resultsetoracle.jdbc.driver.OracleResultSetImpl#762f5aa3
I am able to retrieve data from database if not using preparatory statement. Not sure if the problem with the resultset I am using to see the results.
System.out.println("resultset" + rs);
Please help. Thanks in advance
I am using the following jar (OJDBC6-11.2.0.2.0)
public static void main(String[] argv) {
Connection conn= null;
PreparedStatement pstmt = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("connecting to a database");
//Making JDBC connection
conn = DriverManager.getConnection(url,userName,password);
System.out.println("Database connection successfully");
System.out.println("creating statement");
String query = "select * from event where externaleventid=?";
PreparedStatement pstmt = conn.prepareStatement(query);
//Bind values into the parameters.
pstmt.setString(1,"1256294");
ResultSet rs = pstmt.executeQuery();
System.out.println("resultset" + rs);
conn.close();
} catch(SQLException se){
se.printStackTrace();
} catch(Exception e){
e.printStackTrace();
} finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}
}try {
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
That's not an error. What you are printing out is the toString of the result set, and not the contents of the result set. Try looping through rs.next().
You can do like rs.getString("mycolumn") to get the result for a column named "mycolumn" which is stringlike data (call appropriate methods for appropriate types) but you do have to loop through the result set using next(). The next() method returns a boolean to let you know when you are done. So:
while (rs.next()){
System.out.println(rs.getString("mycolumn"));
}
Both column positions (1,2,3,...) and column names are legitimate ways of addressing the columns
EDIT
In case this is helpful, how you find out number of columns in result set:
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
You can also do like
rsmd.getColumnType(1);
rsmd.getColumnLabel(1);
rsmd.getColumnDisplaySize(1);
to get further information about the column 1 for example.