am trying to insert values to the database but it seems there's a problem with the code if anyone can spot it. I am using a Servlet to get the user input and then sending the inputs to the following class using a method:
#Override
public String createItem(String title, String info, String url, String imageFilename) {
String addItem = title;
Connection conn = null;
try
{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + DBPath);
if (conn == null)
{
System.err.println("Database connection was null:(");
return addItem;
}
Statement stmt = conn.createStatement();
String query = "INSERT INTO items (title, info, URL, image) VALUES (newtitle, newInfo, newUrl, newImage )";
//String query = "INSERT INTO items (title, info, URL, image) VALUES(" + title + "," + info + "," + url +","+ imageFilename +")";
stmt.executeUpdate(query);
stmt.close();
}
catch(Exception e)
{
System.err.println("Exception querying database" + e.toString());
}
finally
{
try
{
conn.close();
}
catch(Exception e)
{
System.err.println("Exception querying database" + e.toString());
}
}
return addItem;
}
I have tried to type the values without using the values passed in the method from the servlet.
I have checked my insert Statement in the Sqlite Manager and its working, i also checked if the values were sent to the above class and it is working and i have tried the connection so it is enabling me to retrieve data from it but not inserting to it. so i have no idea why it is not storing the values in the DB.
This INSERT definitely isn't going to work:
String query = "INSERT INTO items (title, info, URL, image) VALUES (newtitle, newInfo, newUrl, newImage )";
Even if you wanted to store those as string literals, you'd have to use single quotes in the SQL statement like this:
String query = "INSERT INTO items (title, info, URL, image) VALUES ('newtitle', 'newInfo', 'newUrl', 'newImage' )";
To store the actual values instead of the variable names (which I'm guessing is what you want), use a PreparedStatement like this:
PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO items (title, info, URL, image) VALUES (?, ?, ?, ?)"
);
stmt.setString(1, newtitle);
stmt.setString(2, newInfo);
stmt.setString(3, newUrl);
stmt.setString(4, newtitle);
stmt.executeUpdate();
Doing it this way prevents SQL injection attacks.
Related
I'm trying to get the primary auto incremented key from one table and store this in another using MySQL connector and JDBC. Although its giving me this error:
statement.executeupdate() cannot issue statements that produce result
sets.
I think its something to do with the storing of the integer variable but not too sure.
public void insertIntoWorkoutLogs(String field_setNumber, String field_repNumber, String field_weightAmount) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
String insert ="INSERT INTO `workout`.`workoutlogs`" + " (`SetNumber`, `RepNumber` , `WeightAmount`)"
+ "VALUES('" +field_setNumber+"','"+field_repNumber+"','"+field_weightAmount+"')";
statement.executeUpdate(insert);
int workoutID = insertQueryGetId("SELECT workoutID FROM workout");
String insert2 ="INSERT INTO `workout`.`workoutlogs`" + " (`WorkoutID`)"
+ "VALUES('" +workoutID+"')";
statement.executeUpdate(insert2);
connection.close();
}catch(Exception e) {
System.out.println(e);
}
}
public int insertQueryGetId(String query) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
int workoutID=0;
int result=-1;
try {
workoutID = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = statement.getGeneratedKeys();
if (rs.next()){
result=rs.getInt(1);
}
rs.close();
statement.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
I've tried using statement for this, but I'm thinking it may have to be prepared statement for it to work. Expecting to store the auto incremented primary key of one table (workouts) into a field within another table (workoutlogs).
It's because you are passing wrong query. Statement.RETURN_GENERATED_KEYS works with Insert queries not with Select queries.
When you insert a row in database, an auto increment value gets generated and is returned but you are passing a Select statement
As Syed Asad Manzoor said, it will work for you but then you need to remove Statement.RETURN_GENERATED_KEYS and statement.executeQuery() has return type of ResultSet so you need to store the result in ResultSet only.
public void insertIntoWorkoutLogs(String field_setNumber, String field_repNumber, String field_weightAmount) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
String insert ="INSERT INTO `workout`.`workoutlogs`" + " (`SetNumber`, `RepNumber` , `WeightAmount`)"
+ "VALUES('" +field_setNumber+"','"+field_repNumber+"','"+field_weightAmount+"')";
statement.executeUpdate(insert);
**int workoutID = insertQueryGetId("SELECT workoutID FROM workout");** // Line of Concern 1
String insert2 ="INSERT INTO `workout`.`workoutlogs`" + " (`WorkoutID`)"
+ "VALUES('" +workoutID+"')";
statement.executeUpdate(insert2);
connection.close();
}catch(Exception e) {
System.out.println(e);
}
}
public int insertQueryGetId(String query) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/workout","root","");
Statement statement =connection.createStatement();
int workoutID=0;
int result=-1;
try {
// Line of Concern 2
**workoutID = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);**
In line (marked as Line of Concern 1 ..
int workoutID = insertQueryGetId("SELECT workoutID FROM workout"); you are passing query as "SELECT...." and at point marked as Line of Concern 2
workoutID = statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS); you are using executeUpdate.. thats why exception is thrown.
Change statement.executeUpdate(query) to statement.executeQuery(query)..
The INSERT statement needs to have flag RETURN_GENERATED_KEYS.
Then getting the ResultSet would deliver for every insert record the generated key(s).
Also use a PreparedStatement for escaping of strings and against SQL injection.
Use try-with-resources to automatically close the several objects, even with exception or early return.
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/workout", "root", "")) {
String insertSql = "INSERT INTO `workout`.`workoutlogs`"
+ " (`SetNumber`, `RepNumber` , `WeightAmount`)"
+ " VALUES(?, ?, ?)";
try (PreparedStatement statement = connection.prepareStatement(insertSql,
Statement.RETURN_GENERATED_KEYS)) {
statement.setString(field_setNumber);
statement.setString(field_repNumber);
statement.setBigDecimal(field_weightAmount);
statement.executeUpdate();
try (ResultSet rs = statement.getGeneratedKey()) {
if (rs.next()) {
int workoutID = rs.getInt(0);
//... second insert here
}
}
}
}
I'm creating a desktop App where user can import file and retrieve them from database (SQlite) and them see or modify data
So if someone can help me with all this
1.I created database using SQLITE
2.I used button for filechooser then A button save for import to database
Problems
1. Open file (done)
2.saving into database (No)
U can see my code
Mycode open button
public void openfolder (ActionEvent event) throws IOException {
FileChooser fc = new FileChooser();
fc.setInitialDirectory(new File("C:\\Users\\Lenovo\\Documents\\NetBeansProjects\\sogece\\src\\PDFimport"));
fc.getExtensionFilters().addAll(
new ExtensionFilter("PDF Files","*.PDF"));
List<File> selectedFiles = fc.showOpenMultipleDialog(null);
if (selectedFiles !=null){
for(int i =0;i <selectedFiles.size();i++){
listview.getItems().add(selectedFiles.get(i) .getAbsolutePath());
}}else{
System.out.println("file is not valid");
}}
Mycode save button
String query = "INSERT INTO PDFS (liste) VALUES (" + listview.getAccessibleText()
+ ")";
System.out.println("Inserting\n" + query);
insertStatement(query);
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:sogeclair.sqlite");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
stmt.close();
c.commit();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getField(query) + ": " + e.getMessage());
System.exit(0);
}
and the error
Inserting
INSERT INTO PDFS (liste) VALUES (null)
Opened database successfully
Our query was: INSERT INTO PDFS (liste) VALUES (null)
Opened database successfully
Deleting directory
C:\Users\Lenovo\Documents\NetBeansProjects\sogece\dist\run674970846
Then I used another solution for Import PDF but I got this as ERROR
Code
String query = "INSERT INTO PDFS (liste) VALUES (?) "try (PreparedStatement stm = connection.prepareStatement(query) {
//NOTE: Position indexes start at 1, not 0
stm.setString(1, listview.getAccessibleText ());
stm.executeUpdate();
}
error
java.lang.UnsupportedOperationException: Not supported yet. at sogeclair.connection.prepareStatement(connection.java:17) at sogeclair.PlanningController.btninsert(PlanningController.java:285) ... 58.
I went Back to verify the problem but I didn't understand what does it mean
Connection.java :17
class connection { static PreparedStatement prepareStatement(String query) { throw new UnsupportedOperationException("Not supported yet.");
PlanningController.java:285 :try (PreparedStatement stm = connection.prepareStatement(query))
Change this:
String query = "INSERT INTO PDFS (liste) VALUES (" +listview.getAccessibleText ()+ ")";
To this :
String query = "INSERT INTO PDFS (liste) VALUES ('" +listview.getAccessibleText ()+ "')";
VARCHAR type should between two ''
Note
This can cause a syntax error or SQL Injection instead you have to use PreparedStatement
String query = "INSERT INTO PDFS (liste) VALUES (?)";
try (PreparedStatement stm = connection.prepareStatement(query) {
//NOTE: Position indexes start at 1, not 0
stm.setString(1, listview.getAccessibleText ());
stm.executeUpdate();
}
I have a registration page where information for a customer can be entered into 4 text fields, i.e. Customer name, customer address, customer email and customer contact number.
I was wondering how to get the data from the text fields and into the Derby Database in netbeans using Java.
Well, you need to get the text from the fields first, so as follows:
//Replace the textfield names with your textfield variable names
String customerName = txtFieldCustomerName.getText();
String customerAddress = txtFieldCustomerAddress.getText();
String customerEmail = txtFieldCustomerEmail.getText();
String customerContactNumber = txtFieldCustomerContactNumber.getText();
Now that we have all the data, we can perform a database insert
Connection con = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
con = DriverManager.getConnection("jdbc:derby://localhost:1527/myDB;create=true;user=me;password=mine");//Replace this with your information to your database
//now we have a connection, we can perform the insert
pstmt = con.prepareStatement("insert into TABLE_NAME_HERE (customerName, customerAddress, customerEmail, customerContactNumber) VALUES (?, ?, ?, ?)");
pstmt.prepareString(1, customerName);
pstmt.prepareString(2, customerAddress);
pstmt.prepareString(3, customerEmail);
pstmt.prepareString(4, customerContactNumber);
pstmt.executeUpdate(); //execute the insert
} catch(SQLException sqle) {
sqle.printStackTrace();
}
finally { //close the connection after everything is done.
try {
con.close();
pstmt.close();
} catch(SQLException sqle) {
sqle.printStackTrace();
}
}
I am writing a program that pulls data out of one schema, restructures the data to fit a new schema, and then inserts the data into a new database with the new schema. The problem is that, in my test code, the last record is not being inserted into the new database.
I am enclosing a greatly simplified version of the code below, which nonetheless recreates the problem. Can anyone show me how to fix the below so that all records in the recordset are inserted into the destination database? Currently, the below does correctly print out the last record in system.out.println, but yet that last record is not present in the destination table afterwards:
static void migrateDataTest(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection sourceConn = DriverManager.getConnection("jdbc:odbc:source_data_test");
Statement st = sourceConn.createStatement();
Connection destinationConn = DriverManager.getConnection("jdbc:odbc:receive_data_test");
int ClientNumber; String ClientsLastName; String ClientsFirstName;
ResultSet rest = st.executeQuery("SELECT ClientNumber, ClientsLastName, ClientsFirstName FROM sourceTable");
PreparedStatement ps5 = null;
while(rest.next()){
ClientNumber = rest.getInt(1);
ClientsLastName = rest.getString(2);
ClientsFirstName = rest.getString(3);
System.out.println(ClientNumber+", "+ClientsLastName+", "+ClientsFirstName);
ps5 = destinationConn.prepareStatement(
"INSERT INTO destinationTable ("
+ "ClientNumber, FirstName, LastName) VALUES (?, ?, ?)"
);
ps5.setInt(1, ClientNumber);
ps5.setString(2, ClientsFirstName);
ps5.setString(3, ClientsLastName);
ps5.executeUpdate();
destinationConn.commit();
}
ps5.close();
}
catch (ClassNotFoundException cnfe){cnfe.printStackTrace();}
catch (SQLException e) {e.printStackTrace();}
}
EDIT:
As per Lokesh's request, I am putting the entire code block which creates this error below. I just ran it again to confirm that it is printing record 30 in system.out.println, but that the destination table does not contain record number 30. The fact that the skipped record is printing out with system.out.println causes me to believe that the code below contains the error:
static void migrateDataTest(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection sourceConn = DriverManager.getConnection("jdbc:odbc:source_test");
Statement st = sourceConn.createStatement();
Connection destinationConn = DriverManager.getConnection("jdbc:odbc:receive_data_test");
int ClientNumber;
String ClientsLastName;
String ClientsFirstName;
String ClientsMiddleInitial;
Date DOB;
int GenderNumber;
int RaceNumber;
ResultSet rest = st.executeQuery("SELECT ClientNumber, ClientsLastName, ClientsFirstName, ClientsMiddleInitial, DOB, GenderNumber, RaceNumber FROM sourceTable");
PreparedStatement ps5 = null;
while(rest.next()){
ClientNumber = rest.getInt(1);
ClientsLastName = rest.getString(2);
ClientsFirstName = rest.getString(3);
ClientsMiddleInitial = rest.getString(4);
DOB = rest.getDate(5);
GenderNumber = rest.getInt(6);
RaceNumber = rest.getInt(7);
System.out.println(ClientNumber+", "+ClientsLastName+", "+ClientsFirstName+", "+ClientsMiddleInitial+", "+DOB+", "+GenderNumber+", "+RaceNumber);
ps5 = destinationConn.prepareStatement(
"INSERT INTO destinationTable ("
+ "ClientNumber, FirstName, MiddleInitial, LastName, DOB, GenderNumber, RaceNumber) "
+"VALUES (?, ?, ?, ?, ?, ?, ?)"
);
ps5.setInt(1, ClientNumber);
ps5.setString(2, ClientsFirstName);
ps5.setString(3, ClientsMiddleInitial);
ps5.setString(4, ClientsLastName);
ps5.setDate(5, DOB);
ps5.setInt(6, GenderNumber);
ps5.setInt(7, RaceNumber);
ps5.executeUpdate();
destinationConn.commit();
}
ps5.close();
}
catch (ClassNotFoundException cnfe){cnfe.printStackTrace();}
catch (SQLException e) {e.printStackTrace();}
}
The solution, oddly enough, was to create and execute an additional prepared statement after the one that was failing to insert the final value in its recordset. Once I added an additional prepared statement afterwards, the first one began to consistently insert all of its values.
Seems like some nuance in java code that perhaps is missing in the code samples that I posted in my original posting above.
I am trying to insert an email ID to a table in my SQLite3 Database. In my case it successfully creates the table but gives an error while inserting a record in it - "near "#gmail": syntax error". How can i resolve this ? Here is the code -
public void insertData(String emailId, double gtse, long receivedDate) throws ClassNotFoundException, SQLException{
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:testdb.sqlite");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
ResultSet result = statement.executeQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='T1'");
if(!result.next()){
statement.executeUpdate("create table T1 (email TEXT, gtse REAL, receiveddate DATE)");
statement.executeUpdate("insert into T1 values(" + emailId + ", "+ gtse +", "+ receivedDate +")");
}
else{
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
Your core error is that for the insert query you are not enclosing the values to be inserted, in quotes. Your query, after construction, looks something like this:
insert into T1 values(whatever#gmail.com, emailtexthere, 04-07-2013)
When it should be something like this:
insert into T1 values('whatever#gmail.com', 'emailtexthere', '04-07-2013')
The SQL parser chokes while trying to parse your current query, because the syntax is incorrect. The solution to this problem is not simply to enclose the values in quotes though, but rather to use prepared statements. This is because the way you are constructing your query right now is vulnerable to SQL injection attacks. Here is an example of using a prepared statement:
PreparedStatement pStmt = conn.prepareStatement(
"INSERT INTO T1 VALUES(?, ?, ?)");
pStmt.setString(1, emailId);
pStmt.setString(2, gtse);
pStmt.setDate(3, receivedDate);
pStmt.execute();