I'm trying to retrieve result from MS SQL Server using netbeans.
the problem is when I retrieve Arabic words from the database I receive it as ????? .
Any one can help ?
and here is the code:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:yasser");
System.out.println("test");
Statement sta = conn.createStatement();
String Sql = "select * from mainn order by id";
ResultSet rs = sta.executeQuery(Sql);
String res = null;
while (rs.next()) {
res = rs.getString("text");
System.out.println(res);
}
the data in the database is not inserted correctly. while inserting the arabic data into database you should choose UT-8. and change character set of database to AL32UTF8.
After a lot of searching i found a very good workaround which is to cast the column that is in arabic to varbinary and then to get it in your java project as bytes then creating a new string that takes the byte array as a constructor parameter which will use the arabic encoding "Windows-1256" to map the correct values of the arabic characters
here is a sample of the code
SQL select statement :
select cast([column_name] as varbinary(max)) from [table_name] where [condition]
java code :
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery("select cast([column_name] as varbinary(max)) from [table_name] where [condition]");
while (rs.next()) {
byte[] tmp = rs.getBytes("column_name");
String cloumn_value = new String(tmp, "Windows-1256");
//cloumn_value arabic value
}
Related
In ORACLE(11g), in some package I have a function that returning table:
SELECT * FROM TABLE( my_PKG.fnc_myList());
So it works perfectly in Oracle SQL Developer tool, for example. I got rows from the target table in Query Result of SQL Developer.
Question:
Will it work from JAVA (8) code?
I tried the code below:
con = DriverManager.getConnection(...);
String SQLQ = "{SELECT * FROM TABLE( my_PKG.fnc_myList());}";
Statement st =con.createStatement();
rs=st.executeQuery(SQLQ);
while (rs.next()) {
int id = rs.getInt(0);
String name = rs.getString(1);
....
}
But got the error:
java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement
Am I wrong somehwere else or it couldn't work at all through JDBC driver?
You should neither use the braces nor the semi-colon. The braces are sometimes used if only a stored procedure is called. But you have a SELECT statement (even if it contains a function). And the semi-colon is only used in PL/SQL or in tools like SQL developer to separate statements:
con = DriverManager.getConnection(...);
String SQLQ = "SELECT * FROM TABLE( my_PKG.fnc_myList())";
Statement st =con.createStatement();
rs=st.executeQuery(SQLQ);
while (rs.next()) {
int id = rs.getInt(0);
String name = rs.getString(1);
....
}
My application is connected to IBM DB2 iSeries database connected through DataDirect approach using db2.jar in Java. When I run any select query with specific data in where clause it do not detect the value that I pass in where condition. Data type for that column is of CHAR(7) and I am passing a value as 'P544901'. How can I use this or any other 7 char value and db can detect it. Is there any other process that can solve my problem.
Sample Code in Java -
String sql = "SELECT poMast.ORDNO from AMFLIBL.POMAST AS poMast WHERE poMast.ORDNO = ? ";
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);
preparedStatement.setString(1, 'P544901');
ResultSet rs = preparedStatement.executeQuery();
System.out.println("ResultSet : \n");
System.out.println(" VNDNO");
while (rs.next())
{
System.out.println(rs.getString("ORDNO"));
}
try to modify like this (replace simple quote by double quote)
preparedStatement.setString(1, "P544901");
When I run this query:
select character from tbl_Unknown where format(fw,'.###')='48.143' and code='0001'
it returns a result in the Access query interface but when I try to run it from Java it doesn't return a result.
My table (tbl_Unknown):
char_id: autonumber value:1
fw: short text value:'48.1425' Hint:after format it become '48.143'.
code: short text value:'0001'
character: short text value: 'x'
My java code:
public static String getLostedCharacter(String font,String fw, String code) {
Connection conn = ConnectDB.getConnection();
String character = null;
try {
Statement statement = conn.createStatement();
String query = "select character from tbl_"+font+" where format(fw,'.###')='"+fw+"' and code='" + code + "'";
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
character = rs.getString(1);
return character;
}
statement.close();
rs.close();
} catch (SQLException ex) {
return "";
}
return "";
}
Access SQL queries that are run from within the Access application itself can use a wide variety of VBA functions that may not be available (or may behave a bit differently) in Access SQL queries that are run from other applications.
As a workaround, I would suggest this:
String query = String.format(
"select character from tbl_%s " +
"where Trunc((Val(fw)*1000)+0.5)=? and code=?",
font);
PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, (int)(1000 * Double.parseDouble(fw))); // e.g. 48143
ps.setString(2, code);
ResultSet rs = ps.executeQuery();
Edit re: comments
As explained by jamadei, the Format() function as implemented in UCanAccess versions <= 2.0.6.2 produces slightly different results than the Access/VBA implementation for this particular case. Specifically Format(48.1425,".###) returns 48.143 in an Access query but it returns 48.142 in a UCanAccess query. This may be corrected in a future release of UCanAccess. This has been corrected in UCanAccess 2.0.6.3.
Both the mentioned issues(int function and rounding mode "half up" in the format function) have been fixed in the 2.0.6.3.
I'm building a project, and I came across a problem
with a Blob field I created in the database Firebird.
This field would be referring to a field observations, which
I do not want to limit the amount of text which the user will enter.
But I have a problem and do not know how I save and read this field.
I'm using JDBC to use the insert prepareStatement stmt
stmt.set ... - For the blob do not know how to do and also
do not know how to convert the String value for the field
You can use PreparedStatement.setString() and ResultSet.getString() and the Firebird driver will convert it to/from a blob for you if you are using a BLOB SUB_TYPE 1 (aka BLOB SUB_TYPE TEXT). You do need to ensure that your connection characterset is the same as the blob character set, otherwise you could get incorrect characterset conversions.
Other options are to explicitly create a Clob (using Connection.createClob()) and set that on the statement, or to use the setCharacterStream method.
To convert a string to blob, I found this example:
//Convert String to Blob
String data = “hello world”;
java.sql.Blob blob = org.hibernate.Hibernate.createBlob(data.getBytes());
//Convert Blob to String
byte[] bdata = blob.getBytes(1, (int)blob.length());
String data1 = new String(bdata);
Take a look at this example setBlob for a prepared statement. Here's a piece. From their example it looks like you can call setBlob on a PreparedStatement
java.sql.Blob blob = null;
try {
conn = getConnection();
// prepare blob object from an existing binary column
pstmt = conn.prepareStatement("select photo from my_pictures where id = ?");
pstmt.setString(1, "0001");
rs = pstmt.executeQuery();
rs.next();
blob = rs.getBlob(1);
// prepare SQL query for inserting a new row using setBlob()
String query = "insert into blob_table(id, blob_column) values(?, ?)";
// begin transaction
conn.setAutoCommit(false);
pstmt = conn.prepareStatement(query);
pstmt.setString(1, "0002");
pstmt.setBlob(2, blob);
int rowCount = pstmt.executeUpdate();
System.out.println("rowCount=" + rowCount);
// end transaction
conn.commit();
I have a problem with fetching table names from SQL Server 2005. I have succeeded in fetching the table names but the problem is along with the table names VIEWS are also displaying. I need to display only the table names in a dropdown.
My code is:
...
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName="somedb";username=sa;password=1234";
Connection con = null;
Statement st = null;
ResultSet rslt = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
DatabaseMetaData md = con.getMetaData();
ResultSet rrs = md.getTables(null, null, "%", null);
while (rrs.next())
{
System.out.println(rrs.getString(3));
}
Here System.out.println(rrs.getString(3)); statement prints all the table names, but along with view names. I need to avoid printing view names. How can I do it?
you can query to meta data tables on MSSQL server. e.g. select * from sysobjects where xtype = 'u' ;here xtype is type of object and 'u' refers to the table type objects.. see MSSQL server documentation for syntax details
there are two areas:
1/ you not restricted on Db side for view the Metadata
2/ by using aliases return AliasName f.e. Select SomeColumNane as Count returns columnName Count
private ResultSetMetaData metaData; //variable
//intialize rslt("Select .....") and thenarter you can call from rstl
metaData = rslt.getMetaData();
//get Column Class (Varchar, Date, Double....)
String className = metaData.getColumnClassName(column + 1);// packed into try catch finally block
// get column count
int columnCount = metaData.getColumnCount();// packed into try catch finally block
//get Column Name
String columnName = metaData.getColumnName(column + 1);// packed into try catch finally block