inserting byte array into blob column - java

I'm trying to insert byte array into a blob column in sqlite database. I've tried with both setBinaryStream and setBytes, but I'm getting not implemented by SQLite JDBC driver exception. I'm using sqlite-jdbc-3.8.7.jar.What jar should I use to get this work? Thanks!
Here's my code:
public void addDriverData(String prenume,String nume,String telefon,String email,String permis,String parola,byte[] photo) throws SQLException
{ String sql = "INSERT INTO driver(first_name,last_name,phone,email,permit,password,photo)VALUES(?,?,?,?,?,?,?)";
PreparedStatement stm = c.prepareStatement(sql);
stm.setString(1,prenume);
stm.setString(2,nume);
stm.setString(3,telefon);
stm.setString(4,email);
stm.setString(5,permis);
stm.setString(6, parola);
//stm.setBinaryStream(7,new ByteArrayInputStream(photo),photo.length);
stm.setBytes(7, photo);
System.out.println(sql);
stm.executeUpdate(sql);
stm.close();
c.commit();
}

Once a PreparedStatement object has been created with
String sql = "INSERT INTO ...";
PreparedStatement stm = c.prepareStatement(sql);
the object has already processed the sql command text. When the time comes to execute the PreparedStatement all we need to do is
stm.executeUpdate();
(The method call executeUpdate(sql) is intended to be used with Statement objects, not PreparedStatement objects.)

Related

I have problems to insert data into my mysql Database using Java

Can anyone Tell how can I modify my code so I can save data in my Database.
My code is:
private Class nextPage;
#OnEvent(component="submitButton")
Object onSubmitFromSubmitButton()
{
String flag="";
String jndiname="jdbc/TestDB";
DataSource dataSource=null;
try{
dataSource=(DataSource) new InitialContext().lookup("java:comp/env/" + jndiname);
Connection con=dataSource.getConnection();
Statement stm=con.createStatement();
ResultSet rs=stm.executeQuery("insert into recenzii (numeRecenzor,nivelIncredere,idHotel,recenzie) values (?,?,?,?)");
ResultSetMetaData rsmd=rs.getMetaData();
while(rs.next())
{
rs.getString("numeRecenzor");
rs.getString("recenzie");
rs.getInt("nivelIncredere");
rs.getInt("idHotel");
}
}catch (Exception e){flag+=e.toString();}
if (dataSource!=null)
flag+=" succes";
System.out.println("Datele au fost trimise cu succes! "+flag);
return nextPage;
}
}
I tried to put ExecuteUpdate or Execute instead of ExecuteQuery but I got some errors on the code that says it can't convert type int to ResultSet. I am new to this so I would appreciate if anyone could tell me what to modify.
Thank you!
ResultSet object is used to retrieve data from database.
If you want to insert data, you can either supply the data to insert within the query and call stm.executeUpdate("insert ...")
or you can use PreparedStatement (there are more options, but these are easiest).
You may want to try something similar to this:
PreparedStatement preparedStatement = con.prepareStatement("insert into recenzii (numeRecenzor,nivelIncredere,idHotel,recenzie) values (?,?,?,?)");
preparedStatement.setString(1, "val1");
preparedStatement.setString(2, "val2");
preparedStatement.setInt(3, 3);
preparedStatement.setInt(4, 4);
preparedStatement.executeUpdate();

Why does this Query return NULL?

I have a derby users database which I query, when the user clicks login on the application.
However, when I query the users table with the parameter [user] derby returns a null Object instead of the record it ought to return.
Here is my code:
String ssql = "SELECT * FROM USERS WHERE UNAME LIKE ?";
try{
DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());
con = DriverManager.getConnection(url);
sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
sql.executeQuery();
ResultSet rs = sql.getGeneratedKeys();
try{
while (rs.next()) {
if(rs.getString("PW").toCharArray().equals(txt_password.getPassword())){
sql.close();
con.close();
return true;
}
} catch (NPE ...) {...}
}
I tried it multiple times wit a test user with both the pw and the username set to "test"; but I always get the same error.
Why is the recordset always Null?
Thanks for your help :)
The documentation says
ResultSet getGeneratedKeys() throws SQLException
Retrieves any auto-generated keys created as a result of executing this Statement
object.
If this Statement object did not generate any keys, an empty
ResultSet object is returned.
Your select statement isn't generating any keys that's why it's returning an empty ResultSet. You aren't inserting anything hence no keys are being generated.
You can try ResultSet rs = sql.executeQuery();. It should work.
You are using it in wrong way.
The generated keys concept should be used only in the case DML of insert type query but not in the case of select query.
select simply select the rows from the table. In this case there is no chance of any keys getting generated.
In the case of insert query if any column is configured as auto increment or kind of functionality then some keys will get generated. These keys can be caught using Statement.RETURN_GENERATED_KEYS in java.
As you are using select query there is no need of using Statement.RETURN_GENERATED_KEYS.
You just modify below lines and everything will be fine.
sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
sql.executeQuery();
ResultSet rs = sql.getGeneratedKeys();
with
sql = con.prepareStatement( ssql );
sql.setString( 1, cbox_chooseUser.getSelectedItem().toString() );
ResultSet rs = sql.executeQuery();

SQL insert into Quotes wrong

int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,"+u+","+p+",'1')");
I'm getting the error
java.sql.SQLException: Unknown column '(the U variable)' in 'field list';
I know for sure it is 100% the "" but i can't seem to find it where it goes wrong
any help is appreciated!
This is my whole method (I want to learn how to do it with a prepared statement)
public static void connectionDB(String u, String p, String f){
{
try {
String username = "/////////";
String password = "///////";
String url = "///////////////";
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = connection.createStatement();
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')");
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("Database connected!");
}
}
It should be like
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')");
Update:-
You can also look into prepared statements because
Prepared statements are much faster when you have to run the same statement multiple times, with different data. Thats because SQL will validate the query only once, whereas if you just use a statement it will validate the query each time.
Assuming fields are A,B,C,D;
A is int and remains are strings
String insertTableSQL = "INSERT INTO Leden"
+ "(A,B,C,D) VALUES"
+ "(?,?,?,?)";
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "Hello");
preparedStatement.setString(3, "this");
preparedStatement.setString(4, "OP");]
preparedStatement .executeUpdate();
It should be
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')'");
The issue is, that " is used in SQL for objects like columns or tables, whereas ' is used for strings. So in +u+, which seems to not exists in context of your query.
Your query itself should therefore look something like (given, that +u+ and +p+ are strings.
INSERT INTO Leden VALUES (null,'+u+','+p+','1')
If you need to have " inside your columns, it would read like
INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')
Also I would recommend to specify the columns you are inserting to so it looks similar to:
INSERT INTO "Leden" ("col1", "col2", "col3", "col4") VALUES (null,'+u+','+p+','1')
This will prevent your query from failing when extending table definition by another column.
Also using prepared statements could be a good idea here, as it helps you preventing from e.g. SQL injections.

How to insert two strings into my Access database from Java using UCanAccess?

I am trying to add two strings on two separate columns columns of my database using Java but I'm not sure what I am doing wrong. The code I am using
try{
Connection conn = DriverManager.getConnection(
"jdbc:ucanaccess://C:/Users/nevik/Desktop/databaseJava/Employee.accdb");
Statement st = conn.createStatement();
String sql = "Select * from Table2";
ResultSet rs = st.executeQuery(sql);
rs.updateString("user", user);
rs.updateString("pass", pass);
rs.updateRow();
}
catch(SQLException ex){
System.err.println("Error: "+ ex);
}
The first column on my database is user and the next one is pass. I am using UCanAccess in order to access my database.
This is how you normally update a row in java:
String query = "update Table2 set user = ?, pass= ?";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt (1, user);
preparedStmt.setString(2, pass);
// execute the java preparedstatement
preparedStmt.executeUpdate();
First of, you've not updated the position of the current cursor in the ResultSet, which means that it's pointing to nothing...
You could use...
if (rs.next()) {
rs.updateString("user", user);
rs.updateString("pass", pass);
rs.updateRow();
}
But this assumes two things...
You have a database that supports updating values in the ResultSet and
You want to update the existing values.
To insert a value into the database, you should be using the INSERT command, for example...
try(Connection conn = DriverManager.getConnection(
"jdbc:ucanaccess://C:/Users/nevik/Desktop/databaseJava/Employee.accdb")) {
try (PreparedStatement stmt = conn.prepareStatement("INSERT into Table2 (user, pass) VALUES (?, ?)") {
stmt.setString(1, user);
stmt.setString(2, pass);
int rowsUpdated = stmt.executeUpdate();
}
}
catch(SQLException ex){
System.err.println("Error: "+ ex);
}
You might like to take some time to go over a basic SQL tutorial and the JDBC(TM) Database Access trail
As a side note...
You should not be storing passwords in Strings, you should keep them in char arrays and
You should not be storing passwords in the database without encrypting them in some way
#guevarak12
About the original question (how to use updatable ResultSet):
your code is wrong, you have to move the cursor in the right position.
In particular, if you are inserting a new row you have to call rs.moveToInsertRow(); before rs.updateString("user", user).
If you are updating an existent row, you have to move the cursor calling rs.next() and so reach the row to update.
Also you have to create the Statement in a different way:
Statement st =conn.createStatement( ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
See junit examples in the UCanAccess source distribution, class net.ucanaccess.test.CrudTest.
All other comments seem to be correct.

What is the correct way of using preparedStatements in Java to send data to a MySQL database?

I want send the String "Gulliver's Travels" to a sql database from a java application. I tried using preparedStatements but failed. How can I do this?
Here is my code.
private int setData(Connection conn,Object[] data){
String sql = "INSERT INTO book VALUES(?,?)";
PreparedStatement prepStm = conn.prepareStatement(sql);
prepStm.setObject(1,data[0]);
prepStm.setObject(2,data[1]);
return prepStm.executeUpdate();
}
table columns :
bookName : VARCHAR
bookPrice : INT
Error :
SQL Syntax error. Fails to add the name field to the database
If your column types are VARCHAR in the actual database table, then use
prepStm.setString(1,"Gulliver's Travels");
instead of
prepStm.setObject(1,"Gulliver's Travels");
Follow this tutorial to learn more about PreparedStatement and its usage.
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
try with this
This is for the updated question
private int setData(Connection conn,Object[] data){
String sql = "INSERT INTO book VALUES(?,?)";
PreparedStatement prepStm = conn.prepareStatement(sql);
prepStm.setString(1,"Gulliver's Travels");
prepStm.setInt(2,200);
return prepStm.executeUpdate();
}
Setting an object is not what you are supposed to be doing. When you know the data type of the input as well as the data type of the database column, then use the correct setter methods.
private int setData(Connection conn,Object[] data){
String sql = "INSERT INTO book VALUES(?,?)";
PreparedStatement prepStm = conn.prepareStatement(sql);
prepStm.setString(1,"Gulliver's Travels");
prepStm.setFloat(2,200.00);
return prepStm.executeUpdate();
}

Categories