If I have this query from java:
String query="insert into user (..., name, ...) values (..., 'à', ...)";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Spinning?user=root");
PreparedStatement prest = con.prepareStatement(query);
prest.executeUpdate();
In the db I will have a strange character: a diamond with a question mark inside.
Is there any solution to this problem?
Change your connection url to the following:
jdbc:mysql://localhost/Spinning?user=root&useUnicode=true&characterEncoding=utf8
Verify the character set you are using in MySQL DB. You can try "SHOW CREATE TABLE xxxx" to print the table DDL with charset being used.
Verify the character set you are using in JDBC driver. If using MySQL ConnectorJ, you can set charset in the JDBC url.
Related
I am connected to IBM DB2 database with java but data is stored as binary format in database so when I fetch any value it comes as binary or hexdecimal format. How can I convert this in binary data in utf-8 at query level.
Sample code to fetch data -
String sql = "SELECT poMast.ORDNO from AMFLIBL.POMAST AS poMast ";
Class.forName("com.ddtek.jdbc.db2.DB2Driver");
String url = "jdbc:datadirect:db2://hostname:port;DatabaseName=dbName;";
Connection con = DriverManager.getConnection(url, "username","password");
PreparedStatement preparedStatement = con.prepareStatement(sql);
ResultSet rs = preparedStatement.executeQuery();
System.out.println("ResultSet : \n");
System.out.println(" VNDNO");
while (rs.next())
{
System.out.println(rs.getString("ORDNO"));
}
You probably need to use the CAST expression:
SELECT CAST(poMast.ORDNO as VARCHAR(50)) from AMFLIBL.POMAST AS poMast
Adjust the VARCHAR length to your needs. The string is in the database codepage (often UTF-8 these days) and converted to the client/application codepage when fetched.
you can "cast" the result from your select to utf8 like below.
String sql = "SELECT poMast.ORDNO, CAST(poMast.ORDNO AS VARCHAR(255) CCSID UNICODE) FROM AMFLIBL.POMAST AS poMast ";
src: cast db2
In my case, somehow bad UTF-8 data had gotten into varchars in a 1208/UTF-8 DB. Prior to conversion, when querying such data via the JDBC driver, the DB returned -4220 via the JDBC driver. This is fixable at the JDBC driver level by adding this property:
java -Ddb2.jcc.charsetDecoderEncoder=3 MyApp
see:
https://www.ibm.com/support/pages/sqlexception-message-caught-javaiocharconversionexception-and-errorcode-4220
The Db2 LUW Command Line Processor fixed it long ago as an APAR, so this error is only seen via the JDBC driver when the above property is not set.
But, if you want to fix the data in the db, this works:
update <table_name> set <bad_data_col> = cast(cast( <bad_data_col> as vargraphic) as varchar);
1st db2 treats (casts) the bad data as a binary where "anything goes" and then converts (casts) it back to valid UTF-8. After the casts, the JDBC driver shows the same result with or without the special property set and returns no errors.
I want to insert a special character like ✪ into a database.
When I do it like this in the Java code:
String message = "✪";
preparedStatement = connection.prepareStatement("INSERT INTO `messages` (`message`) VALUES (?)");
preparedStatement.setString(1, message);
preparedStatement.executeUpdate();
It just inserts a ? instead of ✪. But when I execute the SQL command on phpMyAdmin it works fine and ✪ is inserted.
The column message in the database is of the type varchar(2048) and collation utf8_general_ci.
And the text file encoding of the java project is UTF-8 as well.
I have added the Parameter ?characterEncoding=UTF-8 to the JDBC URL, as #Mathisca pointed out.
I am using a JDBC connection to fetch data from an Access database.
The database design is not my control. In the database there are columns that have "?" included in their names, for example: Open?, Paid?, and lots more.
When I try to fetch data with a PreparedStatement it gives me an error. The query is:
SELECT Open? FROM tblJobList WHERE WeekEnding=?
I also tried to use brackets like [Open?], but the result is the same.
The error I receive is "Too few parameters ..." as I am pushing only one parameter into the PreparedStatement.
I can not use normal statement because of WeekEnding=? as this value is a Timestamp and I could not manage to work it with Statement. Only prepared statement works here.
Can anyone tell me how to use these kind of column names in a PreparedStatement?
use the " character
"SELECT \"Open?\" FROM tblJobList WHERE WeekEnding=?"
tested this against oracle and appears to work with mssqlserver
How to select a column in SQL Server with a special character in the column name?
Just to update this for current technologies:
While the JDBC-ODBC Bridge and Access ODBC were unable to handle a PreparedStatement with a column name containing a question mark, the UCanAccess JDBC driver handles it just fine, as can be confirmed with the following code:
String connectionUrl = "jdbc:ucanaccess://C:/Users/Public/UCanAccessTest.accdb";
Connection conn = DriverManager.getConnection(connectionUrl);
String sql = "SELECT ID, [Open?] FROM tblJobList WHERE WeekEnding=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDate(1, java.sql.Date.valueOf("2016-01-01"));
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.printf("%d: %s%n", rs.getInt("ID"), rs.getBoolean("Open?"));
}
conn.close();
For more information on UCanAccess, see
Manipulating an Access database from Java without ODBC
I am not sure but you can try // to escape the special meaning of ? and to use it as a normal character. Like:
"SELECT Open//? FROM tblJobList WHERE WeekEnding=?"
You can get something similar to your problem here:
Round bracket in string with JDBC prepared statement
Escaping quotes in MSSQL is done by a double quote, so a '' or a "" will produce one escaped ' and ", respectively.
for a jdbc program, im required to make a connection an excel database. the connection is successfully made but wen entering values into it, its giving an "Operation must use an updateable query" exception.
here s the code:
String url="jdbc:odbc:Sample"; //CHANGE THE DATABASE NAME
Connection conn= DriverManager.getConnection(url,"","");
PreparedStatement prepstat = null;
String insert="INSERT INTO [Sheet1$] ([AccountID], [ProjectID], [PositionID]) VALUES (?,?,?)";
prepstat= conn.prepareStatement(insert);
prepstat.setString(1, accountID);
prepstat.setString(2, projectID);
prepstat.setString(3, positionID);
prepstat.executeUpdate(); // this is where the exception occurs
Did you specifically state that the connection was readwrite in your connection string?
I am not familiar with JDBC, but ODBC would be:
"Driver={Microsoft Excel Driver (*.xls)};" & _
"DBQ=C:\MyFolder\MyWorkbook.xls; ReadOnly=False;"
Excel is read-only by default: http://support.microsoft.com/kb/257819
It was just needed to uncheck the read only while creating the DSN.
i have a string value that i have to insert in mysql database. and i have to escape some literal like (' , " ,% ,) in this string so how can i use regex for that
Don't use regex. Use a database library that escapes things for you, and let it handle this.
Don't try to do this yourself. Let the JDBC driver handle it, by using PreparedStatement instead of concatenating an SQL statement using strings yourself. Example:
Connection conn = ...; // Database connection
PreparedStatement ps = conn.prepareStatement("INSERT INTO MYTABLE (NAME, AGE) VALUES (?, ?)");
ps.setString(1, "Jesper");
ps.setInt(2, 38);
ps.executeUpdate();
If you use PreparedStatement, the JDBC driver will take care of escaping the inserted values correctly for whatever brand and version of the database that you use.