MySQL JDBC Syntax Error - mysql

I am writing a simple database with a query that inserts some data, modifies a entry, deletes it, then prints out the rest.
import java.sql.*;
public class SpotifyDB {
//JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/spotify";
static final int portNumber = 3306;
static final String serverName = "localhost";
static final String dbName = "spotify";
//Database credentials
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//Open a connection to the database
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//Insert data
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "INSERT INTO artist(artist) " +
"values('Muse')";
stmt.executeUpdate(sql);
sql = "INSERT INTO album(album, artist, genre, year)" +
"values('Drones', 'Muse', 'Rock', 2015)";
stmt.executeUpdate(sql);
sql = "INSERT INTO album(album, artist, genre, year)" +
"values('The 2nd Law', 'Muse', 'Rock', 2012)";
stmt.executeUpdate(sql);
sql = ("INSERT INTO songs(song, artist, album, tracknumber, duration)" +
"values('Madness', 'Muse', 'The 2nd Law', 2, '4:41')");
stmt.executeUpdate(sql);
sql = ("INSERT INTO songs(song, artist, album, tracknumber, duration)" +
"values('Mercy', 'Muse', 'Drones', 4, '3:52')");
stmt.executeUpdate(sql);
System.out.println("Records inserted into the table!");
//Update data
String sql1 = "UPDATE songs " +
"SET track number = 1 WHERE song in ('Madness')";
stmt.executeUpdate(sql1);
//Delete data
String sql2 = "DELETE FROM songs " +
"WHERE song = Madness";
stmt.executeUpdate(sql2);
//View records
String sql3 = "SELECT * FROM songs";
ResultSet rs = stmt.executeQuery(sql3);
while(rs.next()) {
//Retrieve by column name
String song = rs.getString("song");
String artist = rs.getString("artist");
String album = rs.getString("album");
String track = rs.getString("track number");
String duration = rs.getString("duration");
//Display the values
System.out.print("Song: " + song);
System.out.print(", Artist: " + artist);
System.out.print(", Album: " + album);
System.out.println(", Track: " + track);
System.out.println(", Duration: " + duration);
}
//Close the connection, clean up running functions
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se) {
//Handle errors for JDBC driver
se.printStackTrace();
}
catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
}
finally {
//finally used to close resources
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2) {
}
try{
if(conn!=null)
conn.close();
}
catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
My SQL Database table is quite simple as well;
CREATE TABLE spotify.`songs` (
`song` varchar(20) NOT NULL,
`artist` varchar(20) NOT NULL,
`album` varchar(20) NOT NULL,
`track number` int(3) NOT NULL,
`duration` varchar(10) NOT NULL,
PRIMARY KEY (`song`),
KEY `songalbum_idx` (`album`),
KEY `songartist` (`artist`),
CONSTRAINT `songalbum` FOREIGN KEY (`album`) REFERENCES `album` (`album`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `songartist` FOREIGN KEY (`artist`) REFERENCES `artist` (`artist`)
ON DELETE CASCADE
ON UPDATE CASCADE);
and the console is returning me this error: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException
I am having trouble seeing where the table columns are not matching up, any help would be appreciated. Thank you!

Column names really shouldn't have spaces, for exactly this reason. But if your column names must have spaces then you need to qualify them with back-ticks exactly as you do in your CREATE TABLE statement:
INSERT INTO songs (song, artist, album, `track number`, duration) VALUES ...
Otherwise after the identifier track the query engine is expecting either a comma (to move on to another identifier) or a close parentheses (to end the list of column identifiers). It finds neither of this, and immediately finds another identifier (number, which may even be a reserved word?). This confuses the query parser.

Related

how do i insert data from jTable to sql

im trying to get the data form this jFrame including the data from the jTable and please consider that the values of the table ( the rows number might change )
I've written this code but its not working and I'm a beginner so please if anyone can help
ive tried this code and no values are being inserted to mysql Table
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
try{
Class.forName("com.mysql.jdbc.DriverManager");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/StudentAttendence","root","Qjrq3Y3d38");
int rows=jTable1.getRowCount();
for(int row = 0; row<rows; row++)
{
String StudentID = (String)jTable1.getValueAt(row, 0);
String Student_Name = (String) jTable1.getValueAt(row, 1);
String Subject_ = (String)subject.getSelectedItem().toString();
String Date_ = (String)date.getDateFormatString();
Boolean Attendance = (boolean) jTable1.getColumnSelectionAllowed();
String query = "Insert into attendance(StudentID,Student_Name,Subject_,Date_,Attendance) values ('"+StudentID+"','"+Student_Name+"','"+Subject_+"','"+Date_+"','"+Attendance+"')";
pst = con.prepareStatement(query);
pst.execute();
}
JOptionPane.showMessageDialog(null, "Successfully Save");
}
catch(Exception e){
JOptionPane.showMessageDialog(this,e.getMessage());
}
}

How to ignore 'table already exists' error in eclipse

I have code in eclipse that creates tables for mysql database, but after the initial creation it throws the error 'table already exists'. Is there a way to ignore this error so that it doesn't appear in the console when executing the code? I'm not sure if to do so I have to do something to my code or if its something to be changed in Eclipse, but in case I included my code below if need be
package project_files;
import java.sql.*;
import javax.swing.JOptionPane;
public class database {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/userdatabase";
// Database credentials
static final String USER = "root";
static final String PASS = "pass1234";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE review " +
"(video_name VARCHAR(45) not NULL, " +
" review_comments VARCHAR(45), " +
" review_star VARCHAR(45), " +
" PRIMARY KEY ( video_name ))";
String sql1= "CREATE TABLE user " +
"(FirstName VARCHAR(45) not NULL, " +
" LastName VARCHAR(45), " +
" City VARCHAR(45), " +
" DOB VARCHAR(45), " +
" Phone Number BIGINT(20), " +
" Email VARCHAR(45), " +
" PRIMARY KEY ( Email ))";
String sql2= "CREATE TABLE video " +
"(video_name VARCHAR(45) not NULL, " +
" video_description VARCHAR(45), " +
" video_city VARCHAR(45), " +
" video_tags VARCHAR(45), " +
" video_subject VARCHAR(45), " +
" PRIMARY KEY ( video_name ))";
stmt.executeUpdate(sql);
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
System.out.println("Created table in given database...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
JOptionPane.showMessageDialog(null, "Tables created successfully");
}//end main
}//end JDBCExample
You could use IF NOT EXISTS:
Prevents an error from occurring if the table exists. However, there is no verification that the existing table has a structure identical to that indicated by the CREATE TABLE statement.
CREATE TABLE IF NOT EXISTS review(...);

"JSP First Connection cause second connection not running when it had ended"

I'm trying to get two data(GenreID & GameID) from two different tables(genre & games) and insert them into another table(games_genre). However, it will close the connection to the database after inserting the GenreID successfully even though i had created another new connection to the database.
I have tried to create connection1 and connection2 to the same database. Connection1 is used to insert GenreID and connection2 is used to insert GameID
<%# page import="java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
String gametitle = request.getParameter("gametitle");
String [] checkbox1 = request.getParameterValues("checkbox");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String connURL ="jdbc:mysql://localhost/assignment?user=root&password=root&serverTimezone=UTC";
Connection conn = DriverManager.getConnection(connURL);
Connection conn2 = DriverManager.getConnection(connURL);
Statement stmt = conn.createStatement();
if (checkbox1!= null){
for(String s: checkbox1){
String sqlStr2 = "Select * FROM genre WHERE GenreName='" + s + "'";
ResultSet rs = stmt.executeQuery(sqlStr2);
while(rs.next()){
String genreid = rs.getString("GenreID");
String sqlStr3 = "INSERT INTO games_genre(GenreID) VALUES ('" + genreid + "')";
int j = stmt.executeUpdate(sqlStr3);
if (j>0) {
out.println("Adding GenreID Successfully!");}
}
}
}
conn.close();
Statement stmt2 = conn2.createStatement();
String sqlStr4 = "Select * FROM games WHERE GameTitle='" + gametitle +"'";
ResultSet rs2 = stmt2.executeQuery(sqlStr4);
if(rs2.next()){
String gameid = rs2.getString("GameID");
String sqlStr5 = "INSERT INTO games_genre(GameID) VALUES ('" + gameid + "')";
int k = stmt2.executeUpdate(sqlStr5);
if (k>0) {
out.println("Adding GameID Successfully!");
}
}
conn2.close();
} catch (Exception e) {
out.println("Error :" + e);
}
Adding Game Successfully! Adding GenreID Successfully! Error :java.sql.SQLException: Operation not allowed after ResultSet closed
I don't understand that why do you need to create two Connection as you need to access same database . So ,just create multiple Statement to execute multiple query like below :
Statement stmt=null;
Statement stmt2=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String connURL ="jdbc:mysql://localhost/assignment?user=root&password=root&serverTimezone=UTC";
Connection conn = DriverManager.getConnection(connURL);
stmt = conn.createStatement();
if (checkbox1!= null){
....
}
<!--using same conn object -->
stmt2 = conn.createStatement();
String sqlStr4 = "Select * FROM games WHERE GameTitle='" + gametitle +"'";
ResultSet rs2 = stmt2.executeQuery(sqlStr4);
if(rs2.next()){
...
}
<!--finally close connection-->
conn.close();
} catch (Exception e) {
out.println("Error :" + e);
}
Note : Also try using PreparedStatement for preventing from Sql Injection as concatenating values into a query string is unsafe .

JDBC pass parameters to sql query

I have
employee(id, name, company, salary);
Need to display data for given id
public static void Connect(String conString, String username, String password, int id) throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection(conString, username, password);
String query = "select * from employee where id = " + id + "" ;
ResultSet rs = null;
Statement stmt = null;
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()){
String name = rs.getString("name");
String company = rs.getString("company");
int salary = rs.getInt("salary");
System.out.println("Name: " + name + "\tCompany: " + company + "\tSalary: " + salary);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But here we are passing the id directly. How can we pass it like parametrized queries (like how we pass ? during PreparedStatement)
in that case your query should be
String query = "select * from employee where id = ?";
instead of Statement you need to create PreparedStatement
PreparedStatement preparedStatement = conn.prepareStatement(query);
and then set your id to the prepared statement
preparedStatment.setInt(1, id);
finally execute the query
resultSet = preparedStatement.executeQuery();
It's old post but I would still like to add my answer.
I don't have enough reputation to comment on #prasad's answer, so I am adding small correction as separate answer. Actually, passing query inside praparedStatement.executeQuery() throws MySQLSyntaxErrorException because still it calls Statement.executeQuery instead of PreparedStatement.executeQuery(). And how do I know? I had to spent ample amount of time in figuring out this issue.
So use PreparedStatement.executeQuery() instead of PreparedStament.executeQuery(query).

How to delete row in database in MySQL using JSP?

This is my function. It gets two parameter id of the product and a name. the function delete with MySQL command a row in a database. I know the that there are missing lines in my code, I'm stuck and I don't know how to finish it. I also know that my SQL line is not correct. I'm not sure if combined the String "name" right.
public static deletePro(int cat, String name) {
DB db = new DB();
String sql = "delete from products where pname=+'name' and catid=" + cat;
ResultSet rs = db.getResultSet(sql);
try {
while (rs.next()) {
Products prod = new Products();
prod.setNamePro(rs.getString(name));
prod.setAmount(rs.getInt(cat));
}
rs.close();
db.closeCon();
} catch (SQLException e) {
e.printStackTrace();
}
return
}
String sql = "delete from products where pname=+'name' and catid=" + cat;
This should be:
String sql = "DELETE FROM products WHERE pname='" + name + "' and catid = " + cat;
And the preferred way is to use PreparedStatement, which would alleviate the pain of string manipulation in your query by using placeholders:
String sql = "DELETE FROM products WHERE pname= ? and catid = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.setInt(2, cat);
ps.executeUpdate();
Hope this helps.