showing thai language from sqlserver in java swing - java

I am facing some problem by getting thai word from sql server 2000 database in java netbeans 7.1
i've made the connection using net.sourceforge.jtds.jdbc.Driver and after making the connection when i want to read the table values (which are stored in thai language) say
เพชรสี่เหลี่ยม
is the desired value to get in a message box (for example) instead my program shows
ྪÃÊÕèàËÅÕèÂÁ
i am using jdk 1.7
here is my code snippet:
PreparedStatement pre = null;
try {
pre = con.prepareStatement("select * from setting");
} catch (SQLException ex) {
Logger.getLogger(NewFrm1.class.getName()).log(Level.SEVERE, null, ex);
}
ResultSet rs;
try {
rs = pre.executeQuery();
while(rs.next())
{
String strthai = rs.getString(3); \\ this is a varchar field in database
ShowMessage( strthai,"coding");
}
} catch (SQLException ex) {
Logger.getLogger(NewFrm1.class.getName()).log(Level.SEVERE, null, ex);
}
I've made this clear by making testing programs in both VB 6.0 and delphi 5 that those test programs are showing the correct thai words (ie เพชรสี่เหลี่ยม ) in their programs for the same table.
I am trying searching a lot and already spent 2 days to resolve this issue
please give me some solution regarding this issue.

Related

Slowness when calling procedure with JPA

sorry my english.
I have a problem for some time and I have no idea what to do to solve it, I have a legacy application in Java 5 that uses JDBC to execute a procedure in the SQL Server database that processes a lot of information, this process occurs perfectly and takes a 30 minutes to complete, now I am migrating this application to Java EE with eclipse link, when calling the same procedure in this new system it takes much longer to complete, it has already run for more than 15 hours, unfortunately I do not have access from DBA to the bank to analyze the processes in more depth.
Apparently the problem occurs when there is a lot of data, because in the test bank the execution time in both systems are similar, now when I run with a bank with more data this anomaly occurs.
I changed the code to get the EntityManager connection and run it with JDBC, but without success.
Currently my code is like this:
public void calcula(Integer idProc) {
pegaConexaoJDBC();
String sql = "{call PRO_EQU_CALCULA(?)}";
CallableStatement st = null;
try {
st = connection.prepareCall(sql);
st.setInt(1, idProc);
st.execute();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
st = null;
}
}
}
I performed several tests for days and did not get a solution, can anyone help me?

HSQLDB not saving updates made through Java

I am trying to add records to a table in an HSQL database through Java.
I have an HSQL database I made through OpenOffice, renamed the .odb file to .zip and extracted the SCRIPT and PROPERTIES files (It has no data in it at the moment) to a folder "\database" in my java project folder.
The table looks like this in the SCRIPT file
CREATE CACHED TABLE PUBLIC."Season"("SeasonID" INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY,"Year" VARCHAR(50))
All fine so far, the database connects just fine in Java with this code:
public void connect(){
try{
String dbName = "database\\db";
con = DriverManager.getConnection("jdbc:hsqldb:file:" + dbName, // filenames prefix
"sa", // user
""); // pass
}catch (Exception e){
e.printStackTrace();
}
}
I have the following code to insert a record into "Season".
public void addSeason(String year){
int result = 0;
try {
stmt = con.createStatement();
result = stmt.executeUpdate("INSERT INTO \"Season\"(\"Year\") VALUES ('" + year + "')");
con.commit();
stmt.close();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println(result + " rows affected");
}
I have a final function called printTables():
private void printTables(){
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM \"Season\"");
System.out.println("SeasonID\tYear");
while(rs.next()){
System.out.println(rs.getInt("SeasonID") + "\t\t" + rs.getString("Year"));
}
}catch (Exception e) {
e.printStackTrace(System.out);
}
}
Now if I run this sequence of functions:
connect();
printTables();
addSeason("2010");
printTables();
I get this output:
SeasonID Year
1 rows affected
SeasonID Year
0 2010
Now when I close the program and start it again I get exactly the same output. So the change made during the first run hasn't been saved to the database. Is there something I'm missing?
It's caused by write delay params in hsqldb, by default has 500ms delay synch from memory to files.
So problem is solved when it's set to false
statement.execute("SET FILES WRITE DELAY FALSE");
or set as you like based on your app behaviour.
So my workaround is to close the connection after every update, then open a new connection any time I want to do something else.
This is pretty unsatisfactory and i'm sure it will cause problems later on if I want to perform queries mid-update. Also it's a time waster.
If I could find a way to ensure that con.close() was called whenever the program was killed that would be fine...

No results found when querying derby database from program

I am new on working with java(Embedded) databases and derby. I am creating a java application in netbeans ide 8.0. I was able to set up the database and insert data on it. I tried to select rows on one of my db's tables and as expected I saw the rows i inserted. But when i try to select from my code/project, it returns no result. The connection is successfully established as per the logs and no errors encountered. I don't know what to do anymore. :(
Here's my code:
try {
Connection con = DriverManager.getConnection("jdbc:derby:AccountingDB"); /* Note use' / 'and not' \' The url above will be different in your system*/
PreparedStatement stmt = con.prepareStatement("SELECT * from app.companies");
ResultSet rs = stmt.executeQuery();
if(rs.next())
{
companySet.addItem(rs.getString("name"));
//System.out.println("Id : "+rs.getInt(1) +" "+" Fruitname :"+rs.getString(2));
}
else
{
System.out.println("No word matching in database");
}
} catch (SQLException err) {
System.out.println(err.getMessage()+ "No matching word in database");
}
i did this on the customize code of my jComboBox.
thanks. I hope I explained my problem well. :(

The driver was unable to create a connection to mysql

I'm programming in java SE and I get an error when trying to access to create a connection to mysql. I can connect to mysql, in fact, the error shows up when running a bucle.
What I do in this program is to check for a String in the table Colors of my database and if it finds nothing it creates this String in the table with an autoincrementing id.
It works fine, but after having checked it for a while it gives me the error.
I attach the image of the error and the code where I create the connection.
public Integer codiColor(String col){
Integer codi=null;
if(col.equals(""))
return 1;
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url, usuari, password);//here is the error
try {
Statement st = con.createStatement();
String sql = "SELECT CODICOL FROM COLORES where COLOR ='"+col+"'";
ResultSet res = st.executeQuery(sql);
if(res.next()){
codi = res.getInt("CODICOL");
}
try { res.close(); } catch (Exception e) {}
try { st.close(); } catch (Exception e) {}
}
catch(SQLException s){
JOptionPane.showMessageDialog(null, "Error:\n"+s.getMessage(),
"ERROR.",JOptionPane.ERROR_MESSAGE);
}
finally{
try { con.close(); } catch (Exception e) {}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return codi;
}
This code is the one that checks if the color already exists or not.
EDIT:
url = "jdbc:mysql://192.168.1.200:3306/mybbdd?zeroDateTimeBehavior=convertToNull";
The problem is that con is evidently a member variable where it should be a local variable. If this piece of code and others like it are called from multiple threads, a con value will be overwritten and therefore lost, so a connection leak will result. You will almost certainly also have other problems due to concurrent use of the connection. Make it a local variable.
NB you haven't needed the Class.forName() line since 2007. The close of the connection, statement, and result set would be redundant if you used try-with-resources. And you should use a prepared statement.
String sql = "SELECT CODICOL FROM COLORES where COLOR =?";
try (con = DriverManager.getConnection(url, usuari, password);
PreparedStatement st = con.prepareStatement(sql);
) {
st.setObject(1, col);
ResultSet res = st.executeQuery();
if(res.next()){
codi = res.getInt("CODICOL");
}
}
catch(SQLException s){
JOptionPane.showMessageDialog(null, "Error:\n"+s.getMessage(),
"ERROR.",JOptionPane.ERROR_MESSAGE);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
I find the way out. I googled the number the java error gave to me and I found that adding a registry key to be able to do more connections should work.
I first did it on the server, to allow more connections from clients but it didn't still work so I tried to do it on my computer and for now it works.
This is the link from microsoft
In your code you giving a new connection on every call but you need to understand your OS allows you Only Limited Connection.
after cross Limit it will Not allow you to make another Connection.
i don't know what's your requirement but if you really need Connection
So better option is that you need to make Connection Pool. If user required a connection to do some task then user can Take Connection from connection Pool and after Work Finished user can return that connection to connection pool.
For Achieve this you need to Design Your Configuration File Or you need Design interface library interface and implement according to your Requirement.

can't make updatable resultset with ucanaccess

I've tried most of the examples found here and the web, but I can't open a MS access database(2002 or 2013) and get an updatable result set using UCanAccess. The same code using the JDBC:ODBC driver/connection/works. I've written short test code to check concur_updatable to check this, so I must be missing something. I'm using JDK 1.7 on a Win7 machine. I also have another machine with the same results.
This works:
/*
class jdbc, for testing jdbc:odbc CONCUR_UPDATABLE.
*/
import java.sql.*;
public class jdbc {
private static String dbFQN;
public static void main(String[] args) {
try {
dbFQN = ("C:\\phil\\programming\\kpjl2002.mdb");
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + dbFQN;
System.out.println("Loading database: " + database);
Connection conn = DriverManager.getConnection(database, "", "");
Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
// Fetch records from table
String selTable = "SELECT * FROM " + "tblLibrary" + " ORDER BY Artist, Cat, Cart";
s.execute(selTable);
ResultSet rs = s.getResultSet();
int concurrency = rs.getConcurrency();
if(concurrency == ResultSet.CONCUR_UPDATABLE)
{
System.out.println("rs is updatable");
} else {
System.out.println("rs Not updatable");
}
s.close();
conn.close();
} //close try
catch (Exception ex) {
ex.printStackTrace();
} //close catch
} //close main method
} //close dbAccess class
The output is that rs is updatable.
This doesn't work:
/*
class ucan, for testing ucanaccess CONCUR_UPDATABLE.
C:\jdk1.7.0_79\jre\lib\ext\ucanaccess-2.0.9.5.jar
C:\jdk1.7.0_79\jre\lib\ext\hsqldb.jar
C:\jdk1.7.0_79\jre\lib\ext\jackcess-2.1.0.jar
C:\jdk1.7.0_79\jre\lib\ext\commons-lang-2.6.jar
C:\jdk1.7.0_79\jre\lib\ext\commons-logging-1.1.1.jar
also present:
C:\jdk1.7.0_79\jre\lib\ext\commons-logging-1.2.jar
C:\jdk1.7.0_79\jre\lib\ext\commons-lang3-3.4.jar
*/
import java.sql.*;
public class ucan {
private static String dbFQN;
public static void main(String[] args) {
try {
dbFQN = ("C:\\phil\\programming\\kpjl2002.mdb");
String database = "jdbc:ucanaccess://" + dbFQN;
System.out.println("Loading database: " + database);
Connection conn = DriverManager.getConnection(database, "", "");
Statement s = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
// Fetch records from table
String selTable = "SELECT * FROM " + "tblLibrary" + " ORDER BY Artist, Cat, Cart";
s.execute(selTable);
ResultSet rs = s.getResultSet();
int concurrency = rs.getConcurrency();
if(concurrency == ResultSet.CONCUR_UPDATABLE)
{
System.out.println("rs is updatable");
} else {
System.out.println("rs Not updatable");
}
s.close();
conn.close();
} //close try
catch (Exception ex) {
ex.printStackTrace();
} //close catch
} //close main method
} //close dbAccess class
the output is that rs is Not updatable. So I cannot update or insert rows in the resultset.
The code posted is the operative part of a larger project, where UCanAccess can read the table and put the contents in a jList and jTextarea, with formatting. When I started writing code to update or add a new record, I ran into the problem.
I apologize if this is a bit long.
Anybody have an idea what I'm missing or doing wrong?
BTW, this is one of my 2 fav sites for good, usable Java answers.
UPDATE:
Got an idea from old co-worker, the original database may have been copied from an original Access97 db. to a 2000 db. I had used 2013 Repair and Compact to make "new" 2002 and 2013 db's. Access must retain '97 type even when doing what I did. So, I created a new 2013 dummy db to test, and UCanAccess will report resultset as updatable. I will try to recreate the record data of the current db in a new database file, and see if that works. I'm hoping this is the problem, since UCanAccess doesn't support updatability with Access97 db's. I'll let ya'll know what I find.
Thanks.
I had used 2013 Repair and Compact to make "new" 2002 and 2013 db's. Access must retain '97 type even when doing what I did. So, I created a new 2013 dummy db to test, and UCanAccess will report resultset as updatable.
The "Compact and Repair Database" feature in Access does not change the database file version. If you have (what you suspect to be) an older-version database file then you should use the "Save Database As" feature under "File > Save & Publish" * to convert the database file to a newer version.
* (... at least that's where it is in Access 2010.)
Well, after a nice weekend of eating brats and drinking good beer at Germanfest, I finally got things working. I decided to scrap the MS Access db and put the 472 records in a SQLite db. With that, I was able to get PreparedStatements to work to display the records in a jList and JTextArea, add a new record and update a couple fields in an existing record within the same run of the test application. Did it both as a command line run GUI and from NetBeans 8.0, so I think my problems are solved. After a couple of summer projects get done, I'll get back to re-writing the original VB app using Java.
Thanks Gord, and everyone here.

Categories