*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>
Related
I'm relatively new to coding and Java. I have an assignment where we build a GUI using JavaFX that interfaces with an oracle database with relevant data to be entered into our GUI product. In our GUI we are supposed to have an Update button which function is to update/alter a specific row in the database after making changes to the data in the GUI textfields/comboboxes. For my update action I have the button linked to I get the error java.sql.SQLSyntaxErrorException: ORA-01729: database link name expected. I have searched online for answers but I don't fully understand what this means and how to solve this issue. I set up my connection in the beginning of my code and included static Connection con; Statement stmt; earlier in my code. Any ideas/help would be appreciated
My code is below:
void updateEmp() {
try {
String updateQuery = "UPDATE employees SET firstname = '"
+ tfFirstName.getText() + "', lastname = '"
+ tfLastName.getText() + "', salary = "
+ tfSalary.getText() + ", title = '"
+ jobTitlesCbo.getValue() + "'";
/*if (getDeptNum(deptTitlesCbo.getValue()) > 0
&& getDeptNum(deptTitlesCbo.getValue()) < 6) {
updateQuery = updateQuery + ", departmentid = '"
+ getDeptNum(deptTitlesCbo.getValue()) + "'";
}*/
updateQuery = updateQuery + " WHERE employeeid = " + tfEmpID;
stmt.executeUpdate(updateQuery);
} catch (Exception e) {
System.out.println("Error: " + e.toString());
e.printStackTrace();
}
}
I'm using twitter4j's streaming API to collect tweets. I'm doing this on java platform. I'm getting a stream of tweets at console but can't store.
public void onStatus(Status status) {
try
{
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/twitterapi";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "twitterapi", "");
String query = " insert into tweets"
+ "(tweet_id,tweet_text,screen_name)" + " values"
+ "('" + status.getId() + "','" +
status.getText() + "', '" +
status.getUser().getScreenName() +"')";
Statement statement = conn.createStatement();
statement.executeUpdate(query);
conn.close();
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
System.out.println("onStatus #" + status.getUser().getScreenName() + " - " + status.getText());
}
Please consider every other thing to be correct since that's already working.
In your insert you have a different number of columns to values. You are not specifying the author_id.
In addition, as DaveH noticed, you're not actually running the SQL command against the server.
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'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 + "')";
I have been trying to get a plugin I am working on to talk to my SQL database, creating tabels, and adding rows seems to work fine but simple SELECT queries are returning an empty ResultSet. The relevant code is below.
queryL=
"SELECT RATING"
+ " FROM USERS"
+ " WHERE UUID = '"
+ UUID +"';";
queryG=
"SELECT RATING"
+ " FROM " + Constants.serverName
+ "_USERS"
+ " WHERE UUID = '"
+ UUID +"';";
try {
stmt=con.createStatement();
rs=stmt.executeQuery(queryL);
if (rs.next()){
r.setLocalRating(rs.getInt(1));
}else{
r.setLocalRating(0);
registerPlayer(UUID,false);
Dungeon.getPlugin(Dungeon.class).log("Player new to server");
}
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try{
stmt=con.createStatement();
rs=stmt.executeQuery(queryG);
if (rs.next()){
r.setGlobalRating(rs.getInt(1));
}else{
r.setGlobalRating(0);
registerPlayer(UUID,true);
Dungeon.getPlugin(Dungeon.class).log("Player new to network");
}
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
As you can see if the ResultSet is empty (player does not yet exist in my database) I call registerPlayer. Register player then throws a duplicate entry for primary key error, so I know the table and the row I am looking for exist.
The following code shows the update queries used inside the registerPlayer method.
if (global){
query=
"INSERT INTO"
//+ Constants.dbName + "."
+ " USERS"
+ " VALUES ('"
+ UUID + "', 0)";
}else{
query=
"INSERT INTO "
//+ Constants.dbName + "."
+ Constants.serverName
+ "_USERS "
+ "VALUES ('"
+ UUID + "', 0)";
}
Finally for completeness, the queries used for creating the tables
String userLocalTable=
"CREATE TABLE IF NOT EXISTS " //+ Constants.dbName + "."
+ Constants.serverName +
"_USERS " +
"(UUID varchar(36) NOT NULL, " +
"RATING int NOT NULL, " +
"PRIMARY KEY (UUID))";
String userGlobalTable=
"CREATE TABLE IF NOT EXISTS " + //Constants.dbName + "."
"USERS " +
"(UUID varchar(36) NOT NULL, " +
"RATING int NOT NULL, " +
"PRIMARY KEY (UUID))";
Any insight into my issue would be greatly appreciated, as far as I can tell the SELECT queries should not be returning empty ResultSets.
Thanks for the input, turns out it was something obvious staring me in the face, QueryL's and QueryG's respective queries needed to be swapped.