while (tokens.hasMoreTokens())
{
keyword = tokens.nextToken();
System.out.println("File= "+fileid+" Keyword=" + keyword);
stmt.executeUpdate(
"INSERT into TEXTVALUEINVERTEDINDEX " + "(FILEID, KEYWORD) values ('"
+ fileid + "', '" + keyword + "')"
);
}
This is the loop in which I'm updating the rows. The problem I'm facing is that when i run this only 1 value gets updated and when I comment the stmt.executeUpdate() line it displays all the possible entries in the database.
You need to use preparedStatements...
PreparedStatement pStmt = connection.prepareStatement("INSERT into TEXTVALUEINVERTEDINDEX (FILEID, KEYWORD) values(?,?)");
while (tokens.hasMoreTokens())
{
keyword = tokens.nextToken();
System.out.println("File= "+fileid+" Keyword="+keyword);
pStmt.setString(1, fileid); //This might be pStmt.SetInt(0, fileid) depending on teh type of fileid)
pStmt.setString(2, keyword);
pStmt.executeUpdate();
}
then using this you can extend to us batch update...
PreparedStatement pStmt = connection.prepareStatement("INSERT into TEXTVALUEINVERTEDINDEX (FILEID, KEYWORD) values(?,?)");
while (tokens.hasMoreTokens())
{
keyword = tokens.nextToken();
System.out.println("File= "+fileid+" Keyword="+keyword);
pStmt.setString(1, fileid); //This might be pStmt.SetInt(0, fileid) depending on teh type of fileid)
pStmt.setString(2, keyword);
pStmt.addBatch();
}
pStmt.executeBatch();
Not sure why your code isn't working though - but this will probably help in the long run...
Your code should work. Make sure the sentence is not throwing any Exceptions when running by surrounding it with a try/catch block:
try {
stmt.executeUpdate("INSERT into TEXTVALUEINVERTEDINDEX " +
"(FILEID, KEYWORD) "+"values ('"+fileid+"', '"+keyword+"')");
} catch (SQLException e) {
e.printStackTrace();
}
You should also consider using a PreparedStament instead since its use is very appropriate for your described scenario:
Something like this:
String sql = "insert into textvalueinvertedindex (fileid, keyword) values (?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
while (tokes.hasMoreTokens()) {
keywords = tokens.nextToken();
pstmt.setString(1, fileid);
pstmt.setString(2, keyword);
pstmt.executeUpdate();
}
pstmt.close();
If you want all updates to be applied at once you can use batch execution, here is an example
Your date range and filter selection contained no results.
Related
I'm currently trying to write a txt file to a mySQL database through a Java program. My database connects correctly through a JDBC driver and I can create tables etc through the program. However when I try to read the text file in I get this error message
java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''FName' , 'SName' , 'DOB') VALUES ('John' , 'McCullough' , '270696')' at line 1
I can't find an error in my SQL code. Here is the rest of the code from the class. Any help would be greatly appreciated.
try (Connection con = DriverManager.getConnection(dbUrl, dbUsername, dbPassword)) {
FileReader file1 = new FileReader("resources/Test.txt");
BufferedReader buffer1 = new BufferedReader(file1);
String read;
while ((read = buffer1.readLine()) != null) {
String[] row = read.split(",");
String fName = row[0];
String sName = row[1];
String DOB = row[2];
String insert = "INSERT INTO chessleague.table1 ('FName' , 'SName' , 'DOB') VALUES ('" + fName + "' , '" + sName + "' , '" + DOB + "')";
ps = con.prepareStatement(insert);
ps.executeUpdate();
ps.close();
}
} catch (Exception ex) {
System.out.println(ex);
}
As mentioned in the comments, don't quote the column names.
The code heavily misuses prepared statements to execute simple SQL. The Connection Class has a createStatement() method that creates a simple statement which is meant for text form SQL commands.
Statement stmt = con.createStatement();
stmt.execute("SELECT * from test.t1");
Prepared statements expect a template that is used to create the SQL statements. Here's an example of how the insert could be done with prepared statement commands.
try (PreparedStatement ps = con.prepareStatement("INSERT INTO chessleague.table1 (FName , SName , DOB) VALUES (?, ?, ?)")) {
ps.setString(0, fName);
ps.setString(1, sName);
ps.setString(2, DOB);
ps.execute();
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
}
I'm trying to run update query on table doctors. The primary key of the table is defined as a composite primary key (deptid, docid). What I'm trying to do is to update field designation, qualification and time based on deptid and docid (by another query).
I believe I'm doing something very silly but I'm not able to find it. Can someone help?
String did= request.getParameter("text1");
String dname = request.getParameter("text2");
String desig = request.getParameter("text3");
String qualification = request.getParameter("text4");
String time = request.getParameter("text5");
String className = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://192.168.10.13";
String user = "root";
String password = "";
PreparedStatement ps;
ResultSet rs;
try {
Class.forName(className);
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/webhospital","root","");
// PreparedStatement prepStmt = (PreparedStatement) conn.prepareStatement("Select * from tbl_userinfo");
ps = (com.mysql.jdbc.PreparedStatement) con.prepareStatement("update doctors set Designation=?,Qualification=?,Time= ? where deptid =? and docid IN(select docid from doctors where doctorname='dname';)");
ps.setString(1, did);
ps.setString(3,desig);
ps.setString(4,qualification);
ps.setString(5,time);
ps.executeUpdate();
} catch (ClassNotFoundException cx) {
out.println(cx);
} catch (SQLException ex) {
Logger.getLogger(MysqlInsertServlet.class.getName()).log(Level.SEVERE, null, ex);
}
ps = (com.mysql.jdbc.PreparedStatement) con.prepareStatement("update doctors set Designation=?,Qualification=?,Time= ? where deptid =? and docid IN(select docid from doctors where doctorname='dname';)");
ps.setString(1, did);
ps.setString(3,desig);
ps.setString(4,qualification);
ps.setString(5,time);
You have 4 question mark but set in wrong order why you don't set like :
ps.setString(1, desig);
ps.setString(2,qualification);
ps.setString(3,time);
ps.setString(4,deptId);
Supplying Values for PreparedStatement Parameters
You must supply values in place of the question mark placeholders (if
there are any) before you can execute a PreparedStatement object. Do
this by calling one of the setter methods defined in the
PreparedStatement class. The following statements supply the two
question mark placeholders in the PreparedStatement named updateSales:
updateSales.setInt(1, e.getValue().intValue());
updateSales.setString(2, e.getKey());
The first argument for each of these setter methods specifies the
question mark placeholder. In this example, setInt specifies the first
placeholder and setString specifies the second placeholder.
One change required in your query is
"where doctorname='dname';)" ==>> "where doctorname='"+dname+"';)"
I think without editing your code it is good to show you an simple example.
PrintWriter out = response.getWriter();
String Title = request.getParameter("Title");
String Artist = request.getParameter("Artist");
String Country = request.getParameter("Country");
String price = request.getParameter("price");
String Year = request.getParameter("Year");
try {
//loading driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//creating connection with the database
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app", "app");
PreparedStatement ps = con.prepareStatement("update COMPACT_DISK set TITLE=?,ARTIST=?,COUNTRY=?,PRICE=?,YEARS=? where TITLE=?");
ps.setString(1, Title);
ps.setString(2, Artist);
ps.setString(3, Country);
ps.setString(4, price);
ps.setString(5, Year);
ps.setString(6, Title);
int i = ps.executeUpdate();
if (i > 0) {
out.println("Compact disk successfully inserted");
}
} catch (Exception se) {
out.println("Error Occured : \n" + se.getLocalizedMessage());
se.printStackTrace();
}
Would you be that kind and tell me whats wrong in here? conn is DriverManager.getConnection(DB_URL)
try {
PreparedStatement prepStmt = conn.prepareStatement(
"UPDATE week SET ?=? WHERE id>=? AND id<=?");
prepStmt.setString(1, s);
prepStmt.setFloat(2, x);
prepStmt.setInt(3, c);
prepStmt.setInt(4, d);
prepStmt.executeUpdate();
} catch(SQLException e) {
System.err.println("Error during data update");
e.printStackTrace();
}
Error is in first line of "try" and it goes like "SQL error or missing database (near "?": syntax error)". I have to add that when I put this statement in cmd with "?" substituted with values it works as charm.
You can't pass column names as parameters to the prepared statement. You can only pass values as parameters :
try {
PreparedStatement prepStmt = conn.prepareStatement(
"UPDATE week SET some_column_name=? WHERE id>=? AND id<=?");
prepStmt.setFloat(1, x);
prepStmt.setInt(2, c);
prepStmt.setInt(3, d);
prepStmt.executeUpdate();
} catch(SQLException e) {
System.err.println("Error during data update");
e.printStackTrace();
}
You cannot pass a column name to the PreparedStatement. What you could do to overcome this is change it in the string.
try {
PreparedStatement prepStmt = conn.prepareStatement(
"UPDATE week SET " + s + " =? WHERE id>=? AND id<=?");
prepStmt.setFloat(1, x);
prepStmt.setInt(2, c);
prepStmt.setInt(3, d);
prepStmt.executeUpdate();
} catch(SQLException e) {
System.err.println("Error during data update");
e.printStackTrace();
}
You should not do ? = ? you should specify the field id = ?...or whatever field you want there.
PreparedStatement prepStmt = conn.prepareStatement(
"UPDATE week SET columnName=? WHERE id>=? AND id<=?");
As it was mentioned you can not pass column names or sql syntax to the PreparedStatement. however you can use String.format() to pass anything to your sql:
try {
String sql = "UPDATE week SET %s=? WHERE id>=? AND id<=?";
sql = String.format(sql , "s")
PreparedStatement prepStmt = conn.prepareStatement(sql);
prepStmt.setFloat(1, x);
prepStmt.setInt(2, c);
prepStmt.setInt(3, d);
prepStmt.executeUpdate();
} catch(SQLException e) {
System.err.println("Error during data update");
e.printStackTrace();
}
sa you can see ? = ? is replaced with %s = ? and later the column name was replaced with String.format and later the String was passed to the PreparedStatement.
however this should not be used pass data because it defies the purpose of PreparedStatements.
I am trying to use the preparedStatement Batch but I am having a problem.
The following code does not give me errors, but it inserts in the table only last key of the map and I do not know why.
It will be surely a very stupid error, but this is the first time I use the addBatch() method..
Class.forName("com.mysql.jdbc.Driver");
this.connect = DriverManager.getConnection("jdbc:mysql://localhost/" + this.database + "?user=" + this.user + "&password=" + this.password);
String s;
for (String key : this.map.keySet())
{
s = ("insert into " + this.database + ".user (nickname) values (?)");
this.preparedStatement = this.connect.prepareStatement(s);
this.preparedStatement.setString(1, key);
this.preparedStatement.addBatch();
}
this.preparedStatement.executeBatch();
Thanks in advance!
Prepare your Statement and query outside of the loop:
s = ("insert into " + this.database + ".user (nickname) values (?)");
this.preparedStatement = this.connect.prepareStatement(s);
for (String key : this.map.keySet())
{
this.preparedStatement.setString(1, key);
this.preparedStatement.addBatch();
}
this.preparedStatement.executeBatch();
You are using the addBatch() method wrong. In your code you are doing the prepareStatement in each iteration of for loop, and this replaces the prepared query each time.
You should only be calling prepareStatement once per batch. You should place the prepared statement before the loop (only one call)
what's wrong with my insert method?
my table has two columns, name, and artist..and timestamp, that too
actually, how do i pass timestamp argument to the insert statement?
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
/*FileWriter dir = new FileWriter(nameOfSong.getText()
+ ".txt");
BufferedWriter buffer = new BufferedWriter(dir);
buffer.write(nameOfSong.getText());
buffer.newLine();
buffer.write(artist.getText());
buffer.newLine();
buffer.newLine();
buffer.write(lyrics.getText());
buffer.close();
*/
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO lyrics1_lyrics1 VALUES(" +
nameOfSong.getText() + ", " + artist.getText() + "");
} catch (Exception z) {
System.err.println("Error: " + z.getMessage());
}
internalFrame.dispose();
}
});
)
Always use PreparedStatement.
String sql="INSERT INTO lyrics1_lyrics1 VALUES (?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1,nameOfSong.getText());
statement.setString(2,artist.getText());
statement.executeUpdate();
statement.close();
connection.close();
The text values need to be surrounded by single quotes ('').
And SQL-escaped to avoid SQL injection attacks, or the first time you have a song by Little Bobby Tables, all your DB are belong to him.
Better yet, use a PreparedStatement, and let the machine do work for you.
You can use prepared statement for it
String query = "INSERT INTO lyrics1_lyrics1(name, artist, timestamp) values(?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, name); // set input parameter 2
pstmt.setString(2, artist);
pstmt.setString(3, new TimeStamp(new Date().getTime()));
You need to add an import statement for the TimeStap;
import java.sql.Timestamp;
or else use
pstmt.setString(3, new java.sql.TimeStamp(new Date().getTime()));
Example: Prepared Statement Insert.
You can find a lot of example in java2s site.
Change the line to:
statement.executeUpdate("INSERT INTO lyrics1_lyrics1 VALUES('" +
nameOfSong.getText() + "', '" + artist.getText() + "'");
This might solve your problem:
statement.executeUpdate("INSERT INTO lyrics1_lyrics1 VALUES('" + nameOfSong.getText() + "', '" + artist.getText() + "')");`