I'm trying to get the integer(age information) in my SQL query using this method
// ...
Integer age = 42;
String sql = "insert into user_info value('" + username + "','" + passcode + "','" + gender + "',age,'" + email + "')";
try {
PreparedStatement preparedStatement = con.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
try {
i = stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
finally i got the result of successfully inserting all the information, username, passcode, gender and email, but for the AGE info, it just shows NULL in my mysql database table, and i have tried so hard to fix this but still got confused, please help me out, thx:)
Correct your code first to and then try.
gender + "'," + age + ",'" + email
Secondly you are not using PreparedStatement in right manner. In PreparedStatement you set the dynamic values and do concatenate the SQL like this. Check this https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html
You got an error in you sql query
String sql = "insert into user_info value('" + username + "','" + passcode + "','" + gender + "',age,'" + email + "')";
This will not insert the age value, so age will be set to his default value (NULL)
Try with this query
String sql = "insert into user_info value('" + username + "','" + passcode + "','" + gender + "','" + age + "','" + email + "')";
Related
I have a MySQL Table which looks like this:
I made some Textfields in my form and saved the input as Strings:
String name = shopname.getText();
String address = streetaddress.getText();
String city = cityname.getText();
String state = statename.getText();
String country = countryname.getText();
String zip = zipcode.getText();
String phonept1 = phonecountryid.getText();
String phonept2 = phoneareaid.getText();
String phonept3 = phoneothernumber.getText();
String phonefull = phonept2 + " " + "(" + phonept1 + ")" + " " + phonept3;
Then I just made an INSERT method which worked well with the old SQLite Database:
conn = DBConnect.Connector();
stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO shopList (name,address,city,state,country,zipcode,phonefull) VALUES(" +name+ "," + address + "," + city + "," + state + "," + country + "," + zip + "," + phonefull + ")");
conn.close();
But now it says:
SEVERE: null
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(22) 222222)' at line 1
Anyone see the syntax error?
ps. (22) 222222 is the tested phonefull input.
conn = DBConnect.Connector();
stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO shopList (name,address,city,state,country,zipcode,phonefull) VALUES('" +name+ "','" + address + "','" + city + "','" + state + "','" + country + "','" + zip + "','" + phonefull + "')");
conn.close();
Try this (I have wrapped your string VALUES in single quotes)
edit:
You are leaving yourself vulnerable to SQL injections by passing string values directly. When possible you want to use the PreparedStatement object and setString method.
I'm having problem with the uniqueidentifier from MySQL which is when i tried to insert an array of data into a table that has a uniqueidentifier datatype in one of the column, it just says conversion failed when converting string to uniqueidentifier.
Here's MySQL block:
if (Gender.trim().equals(""))
z = "Value not enough";
else {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
final String query = "USE [dbtest]" +
"insert into [tablename] ([DepositorID],[Name],[Sex],[DateOfBirth],[Race],[Occupation],[Occupation_others],[AddressLine1],[AddressLine2],[Postcode]," +
"[City],[State],[AgeSah],[TelNo],[HPNo],[Email],[Bank],[BankNo],[CreatedBy],[CreatedOn],[ModifiedBy],[ModifiedOn]) values " +
"('" + nokppv + "','" + Namev + "','" + sex + "','" + Date + "','" + Race + "','" + Occupation + "','" + Occupation2 + "','" + Address + "','" + Address2 +
"','" + Postcode + "','" + City + "','" + State + "','" + agesah + "','" + telno + "','" + Phonev + "','"+ Email +"','"+ Bank +"','"+ BankNo +
"',' "+ chars +"','"+ CreatedOn +"','"+ chars1 +"','" + ModifiedOn + "')";
System.out.println("Query:"+query);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next()){
z = "Registration successful";
isSuccess = true;
}else {
z = "Registration error";
isSuccess = false;
}
}
} catch (Exception ex) {
isSuccess = false;
z = "Exceptions";
System.err.println("Message:"+ex.getMessage());
System.err.println("Cause:"+ex.getCause());
System.out.println("Query:"+query);
}
}
}
return z;
}
The things that I already tried
The column for uniqueidentifier allows null and tried to insert it null, same error.
Tried android GUID code, same error, found out sql server uid are sequential which is different from java uid.
Tried declaring UniqueIdentifier variable from JDBC library, same error.
I did found some post that mention of UID generator thats generate a sequential UID that compatible to SQL UID datatype but the post answer was very vague.
I just need hints or a few example to make my own code I hope I provide enough data. Anyone willing to show me the rope around? BTW I'm using MSSQL 2016
and using Android Studio as Java platform.
Try :
+"CONVERT(uniqueidentifier,'"+chars+"' )"
+"CONVERT(uniqueidentifier,'"+chars1+"' )"
You should get :
values ('840403055141','Shariffah Saralisha binti Syed Ali','P','04-03-1984','K','015','null','No 43, Jalan valera 1/3, Taman Tingtong','null','43900','Sepang','K','Y','null','0123456789','Demo#emailhost.com','123','123',CONVERT(uniqueidentifier,'55555555-2222-2222-2222-222222222222'),'2017-02-16 19:59:22','CONVERT(uniqueidentifier,'22222222-2222-2222-2222-222222222222'),'null')
I am trying to read from a mysql table and I am doing the following:
protected void pushRegisteredStudentsData() {
try {
conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String userID = "SELECT * FROM STUDENT";
rs = stmt.executeQuery(userID);
while (rs.next()) {
int id = rs.getInt("ID");
this.studentID = id;
String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
+ this.moduleCode + "')";
System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
stmt.executeUpdate(insertSql);
}
} catch (SQLException e) {
}
}
..but for some reason,
while (rs.next()) {
int id = rs.getInt("ID");
always returns the same ID, even though the table has different ID's on every line!
Does anyone have an idea why that might be?
Thank you in advance! :(
EDIT:
I was using a single statement to execute 2 updates, which was causing the problem!
It is a bit weird that it returns always the same value because it should only return the first value ONCE.
If you print the stacktrace instead of just catching the exception and doing nothing, you will see that it will print something like:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
You are using THE SAME statement for a Select and then for an Insert. This causes the resultSet that is "attached" to the Statement to close because it is not supposed to be used again.
It can be easily fixed by creating another statement:
String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
+ this.moduleCode + "')";
System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
Statement stmt2 = conn.createStatement();
stmt2.executeUpdate(insertSql);
How to check for given username existence in database at time of insertion in MySQL in Java?
I have the following table in MySQL workbench--
user_id int not null,autoincrement
movie _id int not null
movie_name varchar
user_name varchar
rating int
genre varchar
Now following is the insertion into database--
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:XXXX/Recommendation1", "root",
"XXXXXXXXXXX");
Statement st = con.createStatement();
int i = st
.executeUpdate("insert into Table1(movie_Id,movie_name,user_name,rating,genre) values('"
+ movieId
+ "','"
+ mname
+ "','"
+ pname
+ "','" + ratingr + "','" + genre + "')");
out.println("Data is successfully inserted!");
} catch (Exception e) {
System.out.print(e);
So here is I am only inserting movie id,nmovie name,user name,rating genre and then it gets into database and a user id is provided to it(autoincrement)
What i want that if i give the same name in my user_name option it should not provide the unique autoincremente id but insert all the details with the existing User_id
In other words how to check for given username existence in database?
What you are looking for is the SQL to either update the values if the primary key exists, or insert if it doesnt.
In MySQL the insert only if it doesn't exist has the form
INSERT INTO Table11(...) VALUES(...) ON DUPLICATE KEY UPDATE col11=value1, col2=value2,...
To specify that you want the values to come from the VALUES() section you need to make it the following.
INSERT INTO Table11(...) VALUES(...) ON DUPLICATE KEY UPDATE col1=VALUES(col1), col2=VALUES(col2),...
Full example using your table and column names
"insert into Table1(movie_Id,movie_name,user_name,rating,genre) values('"
+ movieId+ "','"+ mname+ "','"+ pname
+ "','" + ratingr + "','" + genre + "') "
+ "ON DUPLICATE KEY UPDATE "
+ "movie_name=VALUES(movie_name), user_name=VALUES(user_name), "
+ "rating=VALUES(rating), genre=VALUES(genre) "
MySQL ON DUPLICATE KEY reference
As a note, it's better form to use the prepare statement to avoid SQL injection.
String stmt = "insert into Table1(movie_Id,movie_name,user_name,rating,genre) values(?,?,?,?,?) "
+ "ON DUPLICATE KEY UPDATE "
+ "movie_name=VALUES(movie_name), user_name=VALUES(user_name), "
+ "rating=VALUES(rating), genre=VALUES(genre) "
PreparedStatement ps = connection.prepareStatement(stmt);
ps.setObject(1, movie_id);
ps.setObject(2, movie_name);
ps.setObject(3, user_name);
ps.setObject(4, rating);
ps.setObject(5, genre);
ResultSet rs = ps.executeQuery();
*Exception : *
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in UPDATE statement
code is:
String Name = txtName.getText();`
String Email = txtEmail.getText();
String Mobile = txtMobile.getText();
String Address = txtAddress.getText();
String Dob = txtDob.getText();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection("jdbc:odbc:NewPData");
String query = "update Table1 set Name='" + Name + "' , Email='" + Email + "' , Mobile=" + Mobile + ", Address= '" + Address
+ "', DOB=" +Dob + ", where ID=" + Update;
PreparedStatement ps_Statement = connection.prepareStatement(query);
ps_Statement.executeUpdate();
JOptionPane.showMessageDialog(panelID, "Record Updated Successfully");
connection.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
You have a , before the where clause. And DOB if it is a date should come within single quotes. And are you sure Mobile is a integer?
"update Table1 set Name='" + Name + "' , Email='" + Email + "' , Mobile=" + Mobile + ", Address= '" + Address
+ "', DOB='" +Dob + "' where ID=" + Update;
But anyway consider using PreparedStatement with argument passing. The SQL you are using is vulnerable for SQL Injection attacks.
Please try this instead:
String yourFormat = "dd-MMM-yy";
Date yourDateVariable = null;
SimpleDateFormat sdf = new SimpleDateFormat(yourFormat);
try {
yourDateVariable = sdf.parse(Dob);
} catch ( Exception ex ) {
// Do something
}
// Continue your code<code>