Delete data from database using jsp - java

I want to delete a particular record from the database.
My code is given below:
<%
String value = request.getParameter("Meter_No");
int v=Integer.parseInt(value);
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDirver");
Connection conn = DriverManager.getConnection ("jdbc:sqlserver://localhost:1433;databaseName=myDatabase;
user=shakir;password=shakir123");
Statement st = conn.createStatement();
ResultSet rs =st.executeQuery("DELETE * FROM qesco_table
WHERE Meter_No ="+v+"");
rs.close();
conn.close();
}catch(Exception e){
System.out.print(e.getMessage());
}
%>
But it is not deleting the data from database.
Can anyone guide me that where is the problem with the code?

Every thing in your code is fine.
But You need to run your query using st.executeUpdate().
So change the following line
ResultSet rs =st.executeQuery("DELETE * FROM qesco_table WHERE Meter_No ="+v+"");
to
st.executeUpdate("DELETE * FROM qesco_table WHERE Meter_No ="+v);
PLUS
You don't need to have ResultSet in this program as your query is not going to return you any data to store.
You don't need to have empty "" (double quotes) at the end of your query.
You should close connection and others in finally block rather than try block itself.
And better if you try to use PreparedStatements to write dynamic queries. So it will become something like,
<%
String value = request.getParameter("Meter_No");
int v=Integer.parseInt(value);
Connection conn = null;
PreparedStatement pst = null;
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDirver");
conn = DriverManager.getConnection ("jdbc:sqlserver://localhost:1433;databaseName=myDatabase;user=shakir;password=shakir123");
pst = conn.prepareStatement("delete from qesco_table where Meter_No = ?");
pst.setInt(1,v);
pst.executeUpdate();
}catch(Exception e){
System.out.print(e.getMessage());
}finally{
pst.close();
conn.close();
}
%>

To delete a record from data base using JDBC you need to use executeUpdate("your query") method.The executeQuery() query is used when you want to retrieve data from data base.
Then query should be
DELETE FROM qesco_table
WHERE Meter_No ="+v+"
It is not Delete * from table and correct is Delete from table
Change to
st.executeUpdate("DELETE FROM qesco_table WHERE Meter_No ="+v);

try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDirver");
Connection conn = DriverManager.getConnection ("jdbc:sqlserver://localhost:1433;databaseName=myDatabase;user=shakir;password=shakir123");
Statement st = conn.createStatement();
ResultSet rs =st.executeUpdate("DELETE * FROM qesco_table WHERE Meter_No ="+v);
}
catch(SQLException e){
System.out.print(e.getMessage());
}
finally
{
rs.close();
conn.close();
}

I suggest to avoid Scriplet instead use JSP Standard Tag Library and Expression language that is easy to user and less error prone.
One more thing you should move this database code in a servlet and call it from JSP. If you are still interested to do it in JSP then you should use SQL Tag Library that is designed for database access from JSP.
Sample code:
<sql:setDataSource var="dataSource"
driver="com.microsoft.sqlserver.jdbc.SQLServerDirver"
url="jdbc:sqlserver://localhost:1433;databaseName=myDatabase"
user="shakir" password="shakir123" />
<sql:update dataSource="${dataSource}"
sql="DELETE FROM qesco_table WHERE Meter_No =?">
<sql:param value="${param.Meter_No }" />
</sql:update>

try this bro!! it will work for sure 101%
<%
String value = request.getParameter("Meter_No");
int v=Integer.parseInt(value);
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDirver");
Connection conn = DriverManager.getConnection ("jdbc:sqlserver://localhost:1433;databaseName=myDatabase;user=shakir;password=shakir123");
Statement st = conn.createStatement();
String sql = "DELETE FROM qesco_table WHERE Meter_No= '"+v+"'";
st.executeUpdate(sql);
}
catch(Exception e){
System.out.print(e.getMessage());
}
%>

Class.forName("com.mysql.cj.jdbc.Driver");
Connection c=DriverManager.getConnection("jdbc:mysql://localhost:3306/advjava", "root", "root");
Statement stat=c.createStatement();
int del=stat.executeUpdate("Delete from Cart where U_Id="+uid);

Related

MySQL not pushing insert into database with netbeans

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

SQLEXCEPTION Operation not allowed after ResultSet closed error insist

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

hsqldb 2.3.2 jdbc driver does not support ResultSet.first()?

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

java.sql.SQLException:Access denied for user

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!

Not able to retrieve data after executing preparatory statement in Eclipse after JDBC Connection

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.

Categories

Resources