what's wrong with my insert statement? mysql java - java

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() + "')");`

Related

Why am I getting this error: E/ERROR: The executeQuery method must return a result set.?

I'm trying to connect my project with an SQL-Server database. But I always get this error E/ERROR: The executeQuery method must return a result set.
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String username = "un";
String password = "pass";
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://ip/db;user=" + username + ";password=" + password);
Log.w("Connection","open");
String sql = "INSERT INTO TABLE" +
"(Cliente, NomePessoa, Email, NivelSatisfacao, Nota) " +
"VALUES ('" + informacao.getNomeCliente() + "', '" + informacao.getNome() + "', '" + informacao.getEmail() + "', '" + informacao.getSatisfacao() + "', '" + informacao.getNota() + "') ";
Statement stmt = conn.createStatement();
ResultSet rSet = stmt.executeQuery(sql); // error here
I tried to change stmt.executeQuery to stmt.executeUpdate, but it underlines it red, and says that the output is int, so it is incompatible.
Using PreparedStatement is much safer.
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String username = "un";
String password = "pass";
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://ip/db;user=" + username + ";password=" + password);
Log.w("Connection","open");
String sql = "INSERT INTO TABLE" +
"(Cliente, NomePessoa, Email, NivelSatisfacao, Nota) " +
"VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, informacao.getNomeCliente())
pstmt.setString(2, informacao.getNome())
pstmt.setString(3, informacao.getEmail())
pstmt.setString(4, informacao.getSatisfacao())
pstmt.setString(5, informacao.getNota())
int result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
I think you should use the executeQuery method while querying tables in the database (when you have the SELECT keyword). When you want to execute SQL statements (like INSERT, UPDATE and others) you should use execute method, as seen in here.
In your case you could try:
Boolean rSet = stmt.execute(sql);

SQL in Prepared Statement throwing SQL exception

I'm trying to figure out why this code is throwing an SQL exception. When I run this code it prints "Bad SQL in customer insert ps", which is the message in that inner catch block. I've got multiple prepared statements with SQL inserts like this both in this class and also elsewhere in my application. They're all working fine. I've looked through this one over and over again, and I can't figure out why this one is throwing an exception.
try {
Connection conn = DBconnection.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT customerId FROM customer WHERE customerName=\"" + name + "\";");
System.out.println(ps.toString());
ResultSet rs = ps.executeQuery();
if (rs.next()) {
customerId = rs.getString("customerId");
}
try {
PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement("INSERT "
+ "INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)"
+ "VALUES(\"" + name + "\", " + addressId + ", " + active + ", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\");");
customerInsert.executeUpdate();
System.out.println(customerInsert.toString());
System.out.println(rs.toString());
} catch (SQLException sq) {
System.out.println("Bad SQL in customer insert ps");
}
} catch (SQLException customerIdException) {
System.out.println("Bad SQL in customer ps");
}
You're using PreparedStatement as though you were using Statement. Don't put the parameters in the SQL, put in placeholder ? marks. Then use the various setXyz methods (setString, setInt, etc.) to fill in the parameters:
PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement(
"INSERT INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)" +
"VALUES(?, ?, ?, ?, ?, ?, ?);"
);
customerInsert.setString(1, name);
customerInsert.setInt(2, addressId);
// ...etc. Notice that the parameter indexes start with 1 rather than 0 as you might expect

Connecting to database with Java

In preparation for an exam I am asked to debug and answer the questions below, but this goes over my head. Help much appreciated.
Assuming the syntax is correct, why will this code produce an
error when connecting to the database?
Suggest two ways how to improve security of database connection in this code.
import java.sql.*;
public class UpdateCar {
public static void updateCarNum (int carNo, int empNo)
throws SQLException {
Connection con=null;
PreparedStatement pstmt=null;
try {
con = DriverManager.getConnection(
"jdbc:default:connection");
pstmt= con.prepareStatement("UPDATE EMPLOYEES " +
"SET CAR_NUMBER = ? " +
"WHERE EMPLOYEE_NUMBER = " + empNo);
pstmt.setInt(2, empNo);
pstmt.executeUpdate();
}
finally {
if (pstmt != null) pstmt.close();
}
}
}
Change
pstmt= con.prepareStatement("UPDATE EMPLOYEES " +
"SET CAR_NUMBER = ? " +
"WHERE EMPLOYEE_NUMBER = " + empNo);
pstmt.setInt(2, empNo);
to
pstmt= con.prepareStatement("UPDATE EMPLOYEES " +
"SET CAR_NUMBER = ? " +
"WHERE EMPLOYEE_NUMBER = ?");
pstmt.setInt(1, carNo);
pstmt.setInt(2, empNo);
And you should also read a bit about what JDBC is, and how to use it.
Check your DiverManager. in java there is jdbc driver that may not work with your database . try another driver for your connection

Java MySQL preparedStatement Batch

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)

Multiple insert in a loop in jdbc

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.

Categories

Resources