I'm working on a Lab from the Gaddis Java textbook, and I'm attempting to insert an entry into a T-SQL database table of sports teams using a variable to represent the team name.
Code
do
{
// ADD LINES FOR TASK #3 HERE
// Prompt the user for a new team name
System.out.println("Enter new team name: ");
teamName = keyboard.nextLine();
// Update the Teams table
String sqlStatement = "INSERT INTO Teams" +
"VALUES " + teamName + ", 0, 0, 0";
int rows = stmt.executeUpdate(sqlStatement);
System.out.print("Do you want to enter " +
"another team: ");
ans = keyboard.nextLine().charAt(0);
} while(ans == 'Y'|| ans == 'y');
When entering the value Braves
I get the error Incorrect syntax near 'Braves'.
Thanks in advance for any and all assistance!
UPDATE 01
Thanks to feedback I've updated my SQL statement, as well as specifying the column names to ensure the order is correct.
// Update the Teams table
String sqlStatement = "INSERT INTO Teams" +
"(TeamName, Wins, Losses, Ties)" +
"VALUES (" + teamName + " , 0, 0, 0)";
int rows = stmt.executeUpdate(sqlStatement);
However, now I get the error ERROR: Invalid column name 'Braves'.
when entering in Braves
when prompted. I don't understand why as I am specifying the variable teamName
as the value.
SOLVED
Thanks to @MrLY I've solved the issue! Thanks to everyone else that helped as well!
The problem is in your query
String sqlStatement = "INSERT INTO Teams" +"VALUES " + teamName + ", 0, 0, 0";
int rows = stmt.executeUpdate(sqlStatement);
Your insert query should be like this:
INSERT INTO Teams VALUES(att1, att2, att3, ...);
so change your query to be like this:
String sqlStatement = "INSERT INTO Teams " +"VALUES( " + teamName + ", 0, 0, 0)";
if you want to insert a specific attribute then you should to create your query like this:
String sqlStatement = "INSERT INTO Teams(att1, att2, att2, att2) " +"VALUES( " + teamName + ", 0, 0, 0)";
Edit
your String should be between two 'my string'
, so your query should be like this now:
String sqlStatement = "INSERT INTO Teams" +
"(TeamName, Wins, Losses, Ties)" +
"VALUES ('" + teamName + "' , 0, 0, 0)";
NB
I advice to use prepared statement it more useful and more safe than this way
you can learn more about PreparedStatement
You have to write with a good sql syntax. Try something like this :
String sqlStatement = "INSERT INTO Teams " +
"VALUES (" + teamName + ", 0, 0, 0)";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.