may i know whats wrong with my insert sql statement at java as the sql statement allows me to insert everything into database, leaving my profilepic empty. Currently, what im trying to do is that, i am trying to duplicate the image from userId=143 into the new user. However, the duplication of image doesn't work at java.
On the other hand, at mysql database registration table, there is data for userId=143 and with image. I tried to execute the following sql statement and it works prefectly as what i wanted.
insert into registration
(profilepic, firstName,lastName,phoneNo,dateOfBirth,displayname,password,
emailAddress, address, interest )
select (select profilepic from registration where userId =
143),'ab','cd',94329,'2016-11-11','af','de','gf','ge','ee' ;
However, it doesn't work if i use the exact format for sql statement at java. I'm not able to figure out what's wrong with my sql statement. Your help will be much appreciated. Thanks.
try{
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
// connects to the database
conn = getConnection();
// constructs SQL statement
stmt = conn.createStatement();
String sql1 =" insert into registration (profilepic, firstName, lastName,phoneNo,dateOfBirth,displayname,password,emailAddress, address, interest ) select (select profilepic from registration where userId = 143),?,?,?,?,?,?,?,?,? ";
//Using a PreparedStatement to save the file
PreparedStatement statement1 = conn.prepareStatement(sql1);
statement1.setString(1, firstName);
statement1.setString(2, lastName);
statement1.setString(3, phoneNo);
statement1.setString(4, dateOfBirth);
statement1.setString(5, displayName);
statement1.setString(6, password);
statement1.setString(7,emailAddress);
statement1.setString(8, address);
statement1.setString(9, interest);
//sends the statement to the database server
int row = statement1.executeUpdate();
if (row > 0) {
getServletContext().getRequestDispatcher("/Message.jsp").include(request, response);
// message = "You have successfully registered.";
}
} catch (SQLException ex) {
// message = "You have failed to registered. Please try again.";
// ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
// ex.printStackTrace();
//silent
//message="You have failed to log in";
getServletContext().getRequestDispatcher("/FailedMsg.jsp").include(request, response);
}
}
}
Try modifying your query like below having only a single SELECT statement and avoiding the inner sub-select.
insert into registration
(profilepic, firstName,lastName,phoneNo,dateOfBirth,displayname,password,
emailAddress, address, interest )
select profilepic,'ab','cd',94329,
'2016-11-11','af','de','gf','ge','ee'
from registration
where userId = 143;
Related
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();
}
}
I am working on a GUI app with MySQL access. When user enters some data in JTextField 'VendorID', I want it to be searched in the database, find the proper line with information and show all the columns in other JtextFields seperately. Actually I wanted this data to be showed in JLabel but unsuccessful, so trying now with JtextFields. Appreciate any help from you.
public void findVendor() {
String vatEntered = vendorID.getText();
try
{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
Statement st = conn.createStatement();
String check = "SELECT * FROM vendorcreation WHERE VAT = 'vatEntered' ";
ResultSet resultSet = st.executeQuery(check);
boolean status = true;
if(resultSet.next()==status){
nameSelected.setText(resultSet.getString(1));
adressSelected.setText(resultSet.getString(2));
countrySelected.setText(resultSet.getString(3));
vatSelected.setText(resultSet.getString(4));
ptermsSelected.setText(resultSet.getString(5));
conn.close();
}
else {
JOptionPane.showMessageDialog(null, "NO DATA FOUND! FIRST YOU MUST CREATE IT", "Inane error",JOptionPane.ERROR_MESSAGE);
dispose();
new CreateVendor().setVisible(true);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
From what I'm understanding, you're having trouble executing the statement?
You need to set up the statement as following:
String check = "SELECT * FROM vendorcreation WHERE VAT = " +vatEntered ;
But it is better to use a prepared statement instead.
String check = "SELECT * FROM vendorcreation WHERE VAT = ?";
PreparedStatement st = conn.prepareStatement(check);
st.setString(1, vatEntered);
ResultSet resultSet = st.executeQuery();
As for categorizing data, the order seems to depend on the order that the column is in the database. What you can also do is to manually set the result by changing the statement:
String check = "SELECT (column1, column2) FROM vendorcreation WHERE VAT = ?"//etc
where resultSet.getString(1); would be data from column1.
I am developing an app that retrieve data from SQL Server.
I have to execute 2 queries together to come out with result. The problem is the first query is a Stored Procedure that contain (INSERT INTO... EXEC sp_....), this query is shows error in server side but it is executed well, then the second query will read from the inserted result into it sue the first query.
The problem is, when the fist query execute, it make the App goes to Exception part which do not allow the second query to be executed.
Is there any way to make Android Studio ignore the error and execute the second query?
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
message = "Error in connection with SQL server";
} else {
String query = "EXEC [dbo].[sp_ReminderTimeToArriveTheBus]" +
" '"+str_wilayat+"','"+str_city+"', '"+str_station+"', '"+str_distnation+"', '"+currentTime+"'";
PreparedStatement stmt = con.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
rs.next();
String query2 = "SELECT OutputValue FROM [dbo].[FinalResultTable]";
PreparedStatement stmt2 = con.prepareStatement(query2);
ResultSet rs2 = stmt2.executeQuery();
str_min = rs2.getString("OutputValue");
if(rs2.next())
{
message = "O.K.";
str_min = rs2.getString("OutputValue");
isSuccess=true;
}
else{
isSuccess=false;
}
stmt.close();
rs.close();
stmt2.close();
rs2.close();
}
}
catch (Exception ex)
{
message = "Error";
}
return message;
}
If i am understanding the question correctly is query2 should be executed in every situation. You can try running this query in place of "Return message"after catch clause.
I solve the issue through re-write the first query (the stored procedure) and it is executing without errors now.
:)
I am not able to execute an update statement. There seems to be some issue with my update statement.
What I'm doing now is that I'm trying to update the duplicated email address and replace (update) with non-duplicated email. Therefore, in order to update, my SQL statement will check my database against the input and if ((firstname && lastname && dateofbirth) || (phoneNo && address) match what the user input, it will update the database; that is: update the duplicated email address with non-duplicated email, then remove all the duplicated email after the update has been executed.
However, I'm not able to figure out what's wrong. Here is my update statement:
try {
System.out.println("it came here where filepart!=null");
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
// connects to the database
conn = getConnection();
// constructs SQL statement
stmt = conn.createStatement();
//sqll should be update
String sql1 ="UPDATE registration SET emailAddress = ? where ((firstName = ? && lastName= ? && dateOfBirth= ?) || (phoneNo= ? && address= ?))" ;
//Using a PreparedStatement to save the file
PreparedStatement statement1 = conn.prepareStatement(sql1);
System.out.println(firstName+"firstname");
statement1.setString(1, firstName);
statement1.setString(2, lastName);
statement1.setString(3, dateOfBirth);
statement1.setString(4, phoneNo);
statement1.setString(5, address);
statement1.executeUpdate();
statement1.close();
String sql2="delete registration from registration inner join (select min(userId) as lastId, emailAddress from registration where emailAddress in ( select emailAddress from registration group by emailAddress having count(*) > 1) group by emailAddress) duplic on duplic.emailAddress = registration.emailAddress where registration.userId > duplic.lastId";
stmt.executeUpdate(sql2);
//sends the statement to the database server
// if (row > 0) {
// getServletContext().getRequestDispatcher("/Message.jsp").include(request, response);
// message = "You have successfully registered.";
//}
} catch (SQLException ex) {
// message = "You have failed to registered. Please try again.";
// ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
// ex.printStackTrace();
//silent
//message="You have failed to log in";
getServletContext().getRequestDispatcher("/FailedMsg.jsp").include(request, response);
}
}
rs.close();
ps.close();
conn.close();
}}
}
Look at your sql string first:
String sql1 ="UPDATE registration SET emailAddress = ? where ((firstName = ? && lastName= ? && dateOfBirth= ?) || (phoneNo= ? && address= ?))" ;
In the above string you have 6 question marks (placeholders). But you are setting only the five of them and indeed in the wrong way. What you are doing is set firstname for emailAddress, lastname for firstName and so on. The first placeholder(?) is for emailAddress so you have to do as follows:
statement1.setString(1, emailAddress);
statement1.setString(2, firstName);
statement1.setString(3, lastName);
statement1.setString(4, dateOfBirth);
statement1.setString(5, phoneNo);
statement1.setString(6, address);
Can this be a reason you cannot update correctly? You might also be getting some exception. You should look to the RAD console.
The issue might be at where clause. Try to apply Trim() , ToUpper(), or ToLower() function to string data columns and input value. Try to match firstname, lastname, and dateofbirth first. If it works, try with matching phone and address data. Don't forget to clean up/normalize data before you match.
I use MySql database and I use eclipse Java and JDBC to connect. I have a question about SQL statement. I have a table and 4 columns which are id_desk, id_time, user_name and user_passwords. I want to get all informations (all columns information) by using user_name. HOw can i get one row's all informations?
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
//Put your table name instead of TABLE
String query = "SELECT id_desk, id_time, user_name, user_passwords FROM TABLE WHERE user_name = ?";
try {
//Provide your Database credentials
dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER,DB_PASSWORD);
preparedStatement = dbConnection.prepareStatement(query);
//Replace somename with whatever username you querying
preparedStatement.setString(1,"somename");
// execute select SQL stetement
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
//Here you will get the result of the query, ONE row at a time.
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
//Cleanup code
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
The query you would want to use will be similar to:
Select id_desk, id_time, user_name, user_passwords FROM table
WHERE user_name = (whatever your username is)
Storing pure user passwords in a database is not very secure, and you will almost always want to encode them in some way (there are countless resources online with examples of how to do this and why, google them).