I want to read data from database. the data is in arabic language. the character set of my database is AL32UTF8.
when i try to retrive the data i get "????"
please do reply how to solve this problem
this is the code
public static void main(String[] args) {
// TODO Auto-generated method stub
String url = "jdbc:oracle:thin:#localhost:1521:xe";
String username = "hr";
String password = "hr";
String sql = "SELECT WORDS_URDU FROM FINALLY WHERE DFFGG=430";
Connection connection;
try {
connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
while(rs.next())
{
System.out.println(rs.getString(1));
}
//System.out.println(statement.execute(sql));
connection.close();
} catch (SQLException e) {
System.err.println(e);
}
}
The first thing to determine is whether the data in the table is stored correctly. If it is, there's a display problem.
Check if you have set the proper value for NLS_LANG environment variable on the client side where the program is running.
Make sure your terminal program that your program is running in is capable of displaying the required characters.
To determine if the database contents are corrupt, you might try doing 'select dump(words_urdu) from finally where dffgg=430;'. This will show the actual characters that are stored in the database. If the NLS_LANG environment variable was not set correctly at data insertion time, the data may be corrupt in the database.
Hope that helps.
Related
I'm developing a desktop app to organize different events, thus creating a DB for each event. So far, I've managed to create a DB with whatever name the user wants, using a simple GUI.
However, I can't create tables nor columns for said database, even though it's exactly the same syntax I use in SQL Server Manager.
My code so far:
public static void creDB(String db_name, String table_name){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(connectionUrl);
String SQL = "CREATE DATABASE " + db_name;
stmt = conn.createStatement();
int result = stmt.executeUpdate(SQL);
String SQL3 = "USE " + db_name;
boolean ree = stmt.execute(SQL3);
String SQL4 = "GO";
boolean rr = stmt.execute(SQL4);
if (result == 0){
System.out.println("Se insertó :D!");
String SQL2 = "CREATE TABLE Pepe(Name_emp INT NOT NULL PRIMARY KEY)";
int res = stmt.executeUpdate(SQL2);
if (res == 0)
System.out.println("GRACIAS DIOS");
}else
System.out.println("Raios shico");
}catch (Exception e) {e.printStackTrace();}
finally {
if (rs != null) try {rs.close();} catch (Exception e) {e.printStackTrace();}
if (stmt != null) try {stmt.close();} catch (Exception e) {e.printStackTrace();}
if (conn != null) try {conn.close();} catch (Exception e) {e.printStackTrace();}
}
}
The error I get is when I try to actually use the DB, using the use [DB name] go; I tried already using that same syntax in one single SQL statement, however it didn't work, so I tried doing it separately and got this error:
com.microsoft.sqlserver.jdbc.SQLServerException: Could not find stored procedure 'GO'.
I know the code above looks like a mess, and it is, but it's just for testing purposes since I'm new to doing DB-related projects with Java; I mixed-matched some of the concepts of this site, which were successful up until the creation of the tables.
I know there's a better way of managing several databases, but as I said, I'm just starting so any advice would be greatly appreciated.
You should not use statements like USE <dbname> when using JDBC, it may lead to unexpected behavior because parts of the driver may still use metadata for the original connected database. You should either use setCatalog on the current connection to switch databases or create an entirely new connection to the new database.
In short, after creating the database, you should use:
conn.setCatalog(db_name);
That's it.
Also, go is not part of the SQL Server syntax, it is only used by tools like the Management Studio, see What is the use of GO in SQL Server Management Studio & Transact SQL? The equivalent in JDBC is to simply execute the statement.
I am trying to create a new database file named test in the folder D:\sqlite, using JDBC, as follows:
import java.sql.*;
public class Class1 {
private static void createNewDataBase(){
String url = "jdbc:sqlite:D:sqlite/";
Connection conn = null;
Statement statement = null;
try{
conn = DriverManager.getConnection(url);
System.out.println("Connection Established");
statement = conn.createStatement();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
try {
statement.execute("CREATE DATABASE test");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally{
try{
if(statement != null)
statement.close();
}catch(SQLException e){
System.out.println(e.getMessage());
}
try{
if(conn != null)
conn.close();
}catch(SQLException e){
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args){
createNewDataBase();
}
}
When I run the project, I get the following output:
Connection Established
[SQLITE_ERROR] SQL error or missing database (near "DATABASE": syntax error)
Process finished with exit code 0
It says the syntax is wrong but I can't find the error. I've looked for answers for similar questions, but none solved my problem. Can anyone tell me what's the problem? Thanks in advance!
As already stated by #Andreas, there is no CREATE DATABASE SQL statement for SQLite. To create a new SQLite database you need to merely make a connection to one and it is automatically created (you do however need to ensure that the D:/sqlite/ path already exists within the local file system).
The following code should create an empty (no tables) SQLite Database named MyNewDatabase.sqlite within the folder sqlite located in the root of drive D of your local file system:
String dbPath = "D:/sqlite/MyNewDatabase.sqlite";
Connection conn = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + dbPath;);
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
catch (SQLException ex) {
ex.printStackTrace();
}
finally {
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) { e.printStackTrace(); }
}
Now you need to create one or more Tables for your new database to make it useful. SQLite does accept the CREATE TABLE SQL statement and you could do this through the same connection if desired.
The database exists, it has been connected i.e the database is the connection, which is basically the file. Hence there is no SQL for CREATE DATABASE.
Inside the database you would typically create tables (and perhaps other components).
e.g. CREATE TABLE mytable (mycolumn TEXT, myothercolumn INTEGER) which would create a table named mytable with 2 columns mycolumn and myothercolumn (the former being defined with a column type of TEXT, the latter with a column type of INTEGER).
As such, if you were to change :-
statement.execute("CREATE DATABASE test");
to :-
statement.execute("CREATE TABLE mytable (mycolumn TEXT, myothercolumn INTEGER)");
Note you'd only want to do this once, otherwise it would fail as the table already exists, so you could use CREATE TABLE IF NOT EXISTS mytable (mycolumn TEXT, myothercolumn INTEGER), of cousre it depends upon your requirements.
You may find that it will work. Obviously you will need to do other things such as add some data as the table will be empty.
Perhaps then try
statement.execute("INSERT INTO mytable VALUES('fred',100)");
Every time this is run a new ROW will be added to the table name mytable.
Am getting the following error: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "Connection reset by peer: socket write error."
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class SQLDatabaseConnection {
// Connect to your database.
// Replace server name, username, and password with your credentials
public static void main(String[] args) {
String connectionString =
"jdbc:sqlserver://XXXXX.database.windows.net:1433;"
+ "database=VDB;"
+ "user=XXX#VVV;"
+ "password=XXXX;"
+ "encrypt=true;"
+ "trustServerCertificate=false;"
+ "hostNameInCertificate=*.database.windows.net;"
+ "loginTimeout=30;";
// Declare the JDBC objects.
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(connectionString);
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT TOP 2 * from Application";
statement = connection.createStatement();
resultSet = statement.executeQuery(selectSql);
// Print results from select statement
while (resultSet.next()) {
System.out.println(resultSet.getString(2) + " "
+ resultSet.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the connections after the data has been handled.
if (resultSet != null) try {
resultSet.close();
} catch (Exception e) {
}
if (statement != null) try {
statement.close();
} catch (Exception e) {
}
if (connection != null) try {
connection.close();
} catch (Exception e) {
}
}
}
}
I'm only trying to do the "sample" connection snippet of code as referenced on the Azure site (which points to a MS entry), modified only to match my db and test table but without success.
Having reviewed all there is to know, I have:-
ensured that I'm using the right sqljdbc (I've tried all 4)
have the sqlauth.dll on the CLASSPATH
have set the sample up EXACTLY as shown; and incorporated the string that Azure offers.
I have tried various combinations of encrypt and trust without success. As I'm a newbie to Java and Azure, I'm reluctant and unsure how to fiddle with the JVM security settings.
I've proven that my machine can talk to the Azure database (through a VB ODBC connection); and I've tested with the firewall down.
Any thoughts?
I tried to reproduce the issue, but failed that I could access my SQL Azure Instance using the code which be similar with yours.
The difference between our codes is only as below, besides using the connection string of my sql azure instance.
Using the driver sqljdbc4.jar from the sqljdbc_4.0 link.
Using the code Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); to load MS SQL JDBC driver.
Not adding the sqlauth.dll file into the CLASSPATH.
Check my client IP which has been allowed by SQL Azure IP firewall.
Using the sql select 1+1 to test my code, and get the value 4 from code result.getInt(1).
That's fine for me. If you can supply more detals for us, I think it's very helpful for analysising the issue.
Hope it helps.
I just started with sqlite and I stuck with a strange (maybe just for me) phenomenon. When I connect the testDB.db file in java, and make one or some query, the data and the table itself is disappearing. The consol said that SQL error or missing database, and when I check the database file in cmd, the situation is really that; there is no data in the file. Could anybody help me out with this basic problem? (I suppose that this is just because of the lack of my knowledge in this topic, but I'm open to new information)
public class jdbcTest{
public static void main(String[] strg) {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Username\\Documents\\sqlite\\testDB");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30);
//statement.executeUpdate("drop table if exists person");
ResultSet rs = statement.executeQuery("select * from company");
while (rs.next()){
System.out.print("id = "+rs.getInt("id")+" ");
System.out.println("name = "+rs.getString("name"));
}
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
finally {
try {
if (connection!=null){
connection.close();
}
}
catch (SQLException e){
System.err.println(e);
}
}
}
}
When opening a nonexistent database file, SQLite will happily create a new, empty one.
The file name you're giving to getConnection does not actually point to the database you saved.
this program works fine when i connect the java db under the 'Services' tab in netbeans but when i try to open the executable jar file of the prog outside neatbeans it doesn't work at all. I want this java application to be accessible by multiple users as i wish to put it on the my local network so i figured that i need to connect to the Derby database in network mode....am i correct.?.....how should i fix this..?following is code snipet of my application
public void DoConnect() {
try {
/*
** Load the Derby driver.
** When the embedded Driver is used this action start the Derby engine.
** Catch an error and suggest a CLASSPATH problem
*/
Class.forName("org.apache.derby.jdbc.ClientDriver");
try {NetworkServerControl server = new NetworkServerControl();
server.start (null);}
catch(Exception e)
{
System.err.println(e.getMessage());
}
System.out.println(driver + " loaded. ");
} catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
System.out.println("\n >>> Please check your CLASSPATH variable <<<\n");
}
try {
//CONNECT TO THE DATABASE
String host = "jdbc:derby://localhost:1527/Employee";
String uName = "admin";
String uPass = "admin";
//EXECUTE SQL QUERY AND LOAD RESULTSET
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM Workers";
rs = stmt.executeQuery(SQL);
//MOVE CURSOR TO FIRST RECORD AND GET DATA
rs.next();
int id_col = rs.getInt("ID");
String id = Integer.toString(id_col);
String first_name = rs.getString("First_Name");
String last_name = rs.getString("Last_Name");
String job = rs.getString("Job_Title");
//DISPLAY THE FISRT RECORD IN THE TEXT FIELD
textID.setText(id);
textFirstName.setText(first_name);
textLastName.setText(last_name);
textJobTitle.setText(job);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
IMHO it is bad practice to use a Derby database in network mode and to start the server in the same application. You combine all weaknesses of both world :
you cannot access the database from the outside (you server has to be local)
what happens if you server is allready running (if multiple executions on same node) ?
I think it works fine under Netbeans, because Netbeans is doing all the housekeeping for you : starting the server when you access to it via Netbeans interface, and closing it when closing Netbeans.
I think you should try the folowing :
start a server (manually) from outside of your application
remove the code for launching server from your app
(and do not forget to stop server when you have finished with it ...)
By the way I cannot understand what you mean by "not even starting" : if you start it from command line, you should have at least an error message ...
The way you've written the program there is no reason to meddle with the services tab. You should be able to just run (debug) the program directly in NB. Set a breakpoint, debug and step through it. When that works you can try to run from the command line.