I'm trying to fill an SQLite database with data in my java program.
The data is read from an excel file using Apache POI. I have no trouble inserting the data into the db using normal methods.
However, when I check the database manually with the shell, all the Norwegian characters æ,ø,å are not displayed correctly. Whenever I fill out the database manually through the shell, they are displayed as they should.
Also, when printing out a java string in console containing these characters, they are displayed correctly.
The problem must occur when an action like this is performed:
String sql = "insert into db(name) values (æøå)";
stmt.executeUpdate(sql);
I have tried
byte[] b = sql.getBytes("utf-8");
sql = new String(b, "utf-8");
to no avail.
Any idea how to remedy the situation?
Thanks!
There is a very simple solution for you: Let Java and the SQLite driver do everything for you. You don't have to care about encodings and escaping of parameters.
How that is possible: Use a PreparedStatement:
String name = "æøå"
PreparedStatement prepStmt = conn.prepareStatement("insert into db(name) values (?)");
prepStmt.setString(1, name);
prepStmt.executeUpdate();
Furthermore this code fragment is secure against SQL injection attacks.
BTW: The second code fragment you posted is totally useless, it does nothing. Converting a String to byte[] and back to String does not change a single bit of the String.
Related
Using Netbeans, I have my database and table set up, and have added my data manually, in which I am able to see within my application I am building, as intended.
I would like the user to add their own data in which will be appended to a new row on the table. However, I am having trouble trying to write code in order to do this.
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/stockApplication");
Statement stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
String insertDerbyData = "INSERT INTO TIGER_INFO"
+ "(TIGER_ID, TIGER_LOCATION)"
+ "VALUES (123456, Store)";
stat.executeUpdate(insertDerbyData);
I cannot execute the above code as I'm returned with an error mentioning that 'STORE' is not in any table. 'STORE' is meant to be a value for my 'TIGER_LOCATION' column. What's going on here?
In theory, I have two columns, and I would like to add both values, '123456' and 'Store' into their respective columns. How do I go about correctly doing so?
If TIGER_LOCATION is a string/varchar column, and Store is a string literal, then the value must be enclosed in single quotes, as in most SQL-based databases:
INSERT INTO TIGER_INFO (TIGER_ID, TIGER_LOCATION) VALUES (123456, 'Store')
Strings should be between '...' you have to use :
VALUES (123456, 'Store')
//--------------^-----^
I have table called mpi which contains 23 columns. I have introduced the search field with button for every column where user can enter the query to fetch the records using query
query="select * from mpi where Genus ='"+genus+"'
Now I want to fetch records by giving keywords using LIKE %% but it is not working and not giving any records but if type type the full name it is working perfectly. Here is the code
String uname=request.getParameter("uname");
String full="%"+uname+"%";
dbconn=new DatabaseConnection();
conn=dbconn.setConnection();
pstmt=conn.prepareStatement("select * from mpi where Genus LIKE ?");
pstmt.setString(1, full);
res=pstmt.executeQuery
Could any one tell me where is the mistake and why I am not getting the records when I use half keyword like %keyword%.
It works (apart from the missing parentheses) and the approach with a prepared statement is entirely correct.
However I have seen a couple of code pieces like that, and always the problem lay with variables mix-up or not closing, or simple oversight. Better declare as close as possible.
try (ResultSet res = pstmt.executeQuery()) {
while (res.next()) {
..
}
} // Automatically closes res.
Also handle the life-cycle of pstmt correctly, with closing.
Ive been stunk in working with java and mysql these days.
The problem is, ive got a mysql database. There is a column in one table which shows the chinese city names. One collegue changed the db to utf8 for every character(connection, db, results, server and system) The consequence is that the data before the change didn't show correctly any more only if i set the %character% back to latin1. In either character set i can only retrive half the data correctly. Could you please help me how to solve the problem?
Ive tried to use java to solve the problem but it doesn't work.
String sql = "SELECT * FROM customer_addresses";
ResultSet result = query.executeQuery(sql);
while (result.next()) {
byte b[] = result.getBytes("city");
c = new String(result.getBytes("city"), "UTF-8");
}
For example: there is one city in db like this 乌é²æœ¨é½å¸‚
the java print: 乌�?木�?市
it should be:乌鲁木齐市
Thanks in advance
Default charset of your MySQL server is probably not UTF8. Try to execute the following SQL queries before getting data from the database:
SET NAMES utf8
and
SET CHARACTER SET utf8
Add characterEncoding=UTF-8 to the connection string, where you connect to the database. For example:
"jdbc:mysql://servername:3306/databasename?characterEncoding=UTF-8"
Incidentally, the data in the database appears to be broken. If you want the database to store 乌鲁木齐市, that's what should be in the table, not 乌é²æœ¨é½å¸.
Update: The problem with the how the data is stored in the database is easier to solve using database's own tools, not Java. For each table that stores text do this:
ALTER TABLE tablename CONVERT TO CHARACTER SET binary;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8;
I need to store public key in my MySQL DB. I have the following:
rsaModulus=rsaPk.getModulus();
The method getModulus() returns BigInt. But, when I use preparedstatement in order to insert the value in the table, I can not find the approperiate method to do that (i.e, similar to toString, toInt). I need to retrieve this public key and do some mathematical calculations later. That's why, I don't think storing it as String would be a good idea. Also, toLong did not work as the field in the DB is defined as BigInt. Is there any solutions for this problem ??
Files, like keys and certificates generally are stored as a bite array.
This can be done with a blob collumn.
Mysql doc shows about these java type and mysql type relation:
http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-type-conversions.html
If you are able to get your public key as a byte[], use like this sample code:
...
InputStream is = PapelServiceTest.class.getResourceAsStream("MY_FILE_HERE");
byte[] pkBytes = IOUtils.toByteArray(is);
String query = "INSERT INTO my_table (my_key_col) VALUES (?)";
PreparedStatement pstat = conn.prepareStatement(query);
pstat.setBytes(1, pkBytes);
pstat.execute();
...
This thread has an interesting workaround using BLOB.
Store BigInteger into Mysql
Perhaps you can use it.
PS. Next time, search SO first :)
I have an SQLite3 databse I created in python. And by default it writes the database in Unicode.
Now I am trying to query the database in a Java Applet using SQLite JDBC. And I cannot find tables, rows etc because I think Java &/or JDBC queries in ANSI.
Does anyone know how I can query my SQLite3 DB with a unicode query in Java? Something like the following doesn't work (in Java trying to execute a Unicode SQL query):
If I access the database in python I can print out the tables no problem & make updates BUT if I try to do the same in Java, I get no results returned from my query. Is this an encoding problem or some thing else
This works import sqlite3
def blah():
conn = sqlite3.connect( "a.db" )
cur = conn.cursor()
res = cur.execute( "SELECT name FROM sqlite_master WHERE type='table'" ).fetchal()
print res
blah()
This returns no tables when it should return the same tables as above
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:a.db");
Statement stat = conn.createStatement();
conn.setAutoCommit(false);
ResultSet tables = stat.executeQuery("SELECT name FROM sqlite_master WHERE type='table'");
String b = "";
while (tables.next()) { b+= "table= " + tables.getString("name"); }
Jim, that's very odd, it should work. Have you tried to open the DB from the console?
you can open it by running sqlite3 a.db
something that intrigues me, is that you're trying to open the db from a java applet. Have you given it the necessary permissions and signed it, so the apple can actually write to disk?
Have your tired opening the sqlite3 a.db and typing PRAGMA encoding; ? It should say UTF8 by default.
I am able to create a UTF8 sqlite database on the command line and read the contents of that file using sqlite jdbc.
Are you sure you are connecting to the database that you created with python? IF the database does not exist then sqlite will create the database and it will not have any tables in it. This is what is probably happening to you.
Are you running the java and python in the same directory?