This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I have connected my DB with eclipse and i want to give the administrator the permission to delete a member putting the members id from Scanner from a table that I have created
public void processDelete() {
try {
String url = "jdbc:mysql://localhost:3306/labdb";
String user = "****";
String password = "***";
Connection myConn = null;
myStmt = null;
ResultSet myRs = null;
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter the id you want to delete");
int id=keyboard.nextInt();
int rowsAffect=myStmt.executeUpdate(
"delete from members " +
"where member_id='"+id+"' ");
} catch (Exception exc) {
exc.printStackTrace();
}
and i get this error
java.lang.NullPointerException
at DeleteMembers.processDelete(DeleteMembers.java:24)
at main.main(main.java:67)
You get the java.lang.NullPointerException because both your Connection and Statement are null.
You first need to initialize Connection by connectiong with your database.
Use :
Class.forName("YourDriver").newInstance();
to register your databese driver,
myConn = DriverManager.getConnection(dbURL);
To inisialize your Connection
Then you should do :
myStmt = myConn.createStatement()
To inisialize Statement
And after all that you can use your statement to exequte a query in the database
Related
This question already has an answer here:
Problem with adding rows with JDBC and MySQL?
(1 answer)
Closed 4 years ago.
I am having a problem with updating a result set given by mssql.
I want to update a column (initial_deposit) in the table (createaccount with a primary key id) with a new value that is found after adding (initial and the AmountDeposited). AmountDeposited is entered as a double on a textField named (textFieldamount) and initial is also a double value from the result set.
I am getting an error. (Result Set not updatable (referenced table has no primary keys).
This result set must come from a statement that was created with a result set type of ResultSet.CONCUR_UPDATABLE.)
Here is my code
String url = "jdbc:mysql://localhost:3306/STATTER_BANK";
String user = "root";
String password = "";
double amountDeposited = Double.parseDouble(textFieldamount.getText());
public void theQuery {
String query1 = "SELECT initial_deposit FROM createaccount"+"WHERE id=1";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement stt = con.prepareStatement(query1, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stt.executeQuery();
while (rs.next()) {
double initial = rs.getDouble("initial_deposit");
rs.updateDouble( "initial_deposit", initial + amountDeposited);
rs.updateRow();
}
} catch (Exception e ) {
e.printStackTrace();
}
}
You can refer.
similar question perhaps it is the same one
Changing ResultSet.TYPE_SCROLL_SENSITIVE with ResultSet.TYPE_SCROLL_INSENSITIVE should work.
This question already has answers here:
ResultSet exception - before start of result set
(6 answers)
java.sql.SQLException: Before start of result set [duplicate]
(2 answers)
SQLException : Before start of result set
(2 answers)
Closed 4 years ago.
I am trying to retrieve a specific integer value from a column 'Balance' in my Database. However, i keep on catching an exception in my try-catch and this is the output;
Got an exception!
Before start of result set
Here is my code. Any suggestions would be greatly appreciated.
private void OKbtnActionPerformed(java.awt.event.ActionEvent evt)
{
try{
String password = PassJP.getText();
int passint = Integer.parseInt(password);
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/banking application","root","");
String query = "SELECT Balance FROM user WHERE Password =" +passint;
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
int balance = rs.getInt("Balance");
String WAmmount = WithAmmTF.getText();
int WAmmountint = Integer.parseInt(WAmmount);
int newbalance = balance - WAmmountint;
Statement s=conn.createStatement();
s.executeUpdate("INSERT INTO `user`(Balance) VALUE ('"+newbalance+"') where Password="+ passint);
conn.close();
}
catch (SQLException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
EDIT:
i have also tried adding a while loop but that brought me another error like so:
Got an exception!
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 'where Password=111' at line 1
Here is the code
private void OKbtnActionPerformed(java.awt.event.ActionEvent evt)
{
try{
String password = PassJP.getText();
int passint = Integer.parseInt(password);
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/banking application","root","");
String query = "SELECT Balance FROM user WHERE Password = "+passint;
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()) {
int balance = rs.getInt("Balance");
String WAmmount = WithAmmTF.getText();
int WAmmountint = Integer.parseInt(WAmmount);
int newbalance = balance - WAmmountint;
Statement s=conn.createStatement();
s.executeUpdate("INSERT INTO `user`(Balance) VALUE ('"+newbalance+"') where Password="+ passint);
}
conn.close();
}
catch (SQLException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
This question already has answers here:
Mysql Syntax error while inserting from Servlet using preparedstatement
(2 answers)
Java MYSQL Prepared Statement Error: Check syntax to use near '?' at line 1
(2 answers)
Closed 5 years ago.
In this code I want to display single record where the input is taken from the user, but it shows "You have an error in your SQL syntax".
import java.sql.*;
import java.util.Scanner;
public class Display {
public static void main(String[] args) throws ClassNotFoundException{
try{
Scanner scan= new Scanner(System.in);
String driver = "com.mysql.jdbc.Driver", u_name="root", pwd="123456", url="jdbc:mysql://localhost:3306/student";
Class.forName(driver);
Connection con=DriverManager.getConnection(url, u_name, pwd);
if(con!=null)
System.out.println("Connection Successful!");
System.out.print("Enter the Enrolment to be Updated: ");
String en=scan.next();
String qry="SELECT * FROM studentdb WHERE enrolment = ?";
PreparedStatement stmt=con.prepareStatement(qry);
stmt.setString(1, en);
ResultSet result = stmt.executeQuery(qry);
result.next();
System.out.print(result.getString(1)+"\t\t"+result.getString(2));
}
catch(SQLException e){
System.out.println("Error: "+e);
}
}
}
This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 7 years ago.
I want to get the last inserted ID as long. Because the primary key of my table is of long data type.
Here's my code:
Connection connection = null;
Statement statement = null;
try {
String sql = "INSERT INTO testTable(name) VALUES('Anonym')";
connection = DriverManager.getConnection(DB_URL, USER, PASS);
statement = connection.createStatement();
long lastInsertedID = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
System.out.println("LAST INSERTED ID = "+lastInsertedID);
} catch (Exception e) {
e.printStackTrace();
}
I've tested that when the maximum value of integer reaches I get last 1 as last inserted_id.
By the way, I've gone through this post.
Thanks.
try with the following code snippet:
ResultSet rs= statement.getGeneratedKeys();
if (rs.next())
{
System.out.println("Last Inserted ID = "+rs.getLong(1));
}
Here's the full code:
Connection connection = null;
Statement statement = null;
try {
String sql = "INSERT INTO testTable(name) VALUES('Anonym')";
connection = DriverManager.getConnection(DB_URL, USER, PASS);
statement = connection.createStatement();
long lastInsertedID = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs= statement.getGeneratedKeys();
if (rs.next())
{
System.out.println("Last Inserted ID = "+rs.getLong(1));
}
} catch (Exception e) {
e.printStackTrace();
}
This question already has answers here:
mysql prepared statement error: MySQLSyntaxErrorException
(2 answers)
Closed 8 years ago.
I've spent hours looking at what seems like what should be perfectly working code. The connection.createStatement() version of this method works fine but as soon as I try to convert it over to the better, connection.prepareStatement() version it throws a MySQLSyntaxErrorException and complains about a problem near the '?' character in my query string. The code is posted below and I simply cannot see the problem with it. The database field is VARCHAR and accepts Strings so that is not the problem.
public Discussion getDbDiscussionInstance(String _instanceId) throws SQLException {
String qryStr = null;
PreparedStatement myStmt = null;
ResultSet myRs = null;
// Try to build the object with existing data.
try {
qryStr = "SELECT assignment_id, discussion_id, section_id, user_id, circle_id, breakout_id, title, description, created, due FROM macb_discussions WHERE instance_id=?";
myStmt = connection.prepareStatement(qryStr);
myStmt.setString(1, _instanceId);
myRs = myStmt.executeQuery(qryStr);
if (rs.next()) {
this.discussionId = myRs.getString("discussion_id");
}
} catch (SQLException e) {
dbFunc.catchSQLException(e);
} finally {
myRs.close();
myStmt.close();
}
}
Use only myStmt.executeQuery(); without the argument, you have already preperad the statement
From the docs,
Statement.executeQuery(String sql)
PreparedStatement.executeQuery()
So change your function accordingly.
myStmt = connection.prepareStatement(qryStr); to
myStmt = connection.prepareStatement();