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.
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.
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 want to connect to PostgreSQL database in java, which is on Amazon EC2.
I can connect to it using a postgres client on Mac called Postico.
I specify next info:
Nickname
Host (ec2-xx-xx-xx-xx.xx-xx-x.compute.amazonaws.com)
User
Password
Database name
SSH host
User
Password - blank
Private key - .pem file
I could not find any example about how to connect it in Java.
I found some RedshiftJDBC driver and added it to project.
than I tried this:
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("MySQL JDBC Driver Registered!");
try {
this.connection = DriverManager.getConnection("jdbc:postgresql://" +DNS+"/"+myDBname, MYSQLUSER, MYSQLPW);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
I knew it would not work, but at least I tried))
I have no idea how to specify Private key in request (how to send it), or whatever.
Could someone help me ?
Thank you.
Try this the below code with PostgreSQL JDBC driver. You want to make the code a bit more resilient (e.g. check db for null in-between connecting and sending a query, etc.), but this should get you going.
private final String DB_HOST = "YOUR_EC2_HOSTNAME";
private final String DB_PORT = "5432";
private final String DB_USER = "YOUR_POSTGRES_USERNAME";
private final String DB_PASSWD = "YOUR_POSTGRES_PASSWORD";
private final String DB_NAME = "YOUR_POSTGRES_DBNAME";
private final String DB_URL = "jdbc:postgresql://" + DB_HOST + ":" + DB_PORT + "/" + DB_NAME;
private final String INSERT = "INSERT INTO articles (date, name, uuid) VALUES (?, ?, ?)";
private Connection db = null;
public PostgreSQLService() {
try {
Class.forName("org.postgresql.Driver");
db = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWD);
} catch (ClassNotFoundException | SQLException ex) {
log.error(ex);
}
try (PreparedStatement st = db.prepareStatement(INSERT)) {
st.setEscapeProcessing(false);
st.setDate(1, new java.sql.Date(DateUtil.getToday().getTime()));
st.setString(2, "YOUR_NAME");
st.setObject(3, UUID.randomUUID());
if (st.executeUpdate() <= 0) {
throw new PostgreSQLServiceException("0 rows inserted while trying to insert a new row ::: " + st.toString());
}
} catch (SQLException sqle) {
throw new PostgreSQLServiceException("Received an SQLException trying to insert a row", sqle);
}
}
The Maven dependency is:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4.1208</version>
</dependency>
Note, you need to open up port 5432 in that EC2 instance's security group if you're executing this code from outside AWS.
I would also suggest looking at Amazon RDS. You can connect to it with the above code just the same as a Postgres instance running on EC2.
I hope this helps!
You don't specify that SSH info (SSH host, private key, etc.) when connecting from Java. The JDBC driver expects to be able to connect directly to the database server and does not support SSH tunneling. If you need to use SSH tunneling then you would have create that connection separately before starting the Java application.
If the Java application is running on AWS then you should be able to configure the network to allow a direct connection. If you are testing your Java application locally and need to connect to the remote database, then you run the ssh command locally to open a tunnel first. See this documentation: http://www.postgresql.org/docs/8.2/static/ssh-tunnels.html or this answer: PostgreSQL via SSH Tunnel
So I've been teaching myselft mysql and am trying to integrate it into my Java code. I've looked at some past code snippets and tutorials and I can't seem to figure out why my code is incorrect. (removed password for obvious reasons)
Here's what I'm using to connect
public static void connectionToMySql(){
String host = "mysql9.000webhost.com";
String username = "a9808220_pin";
String pass = "";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.getConnection(host,username,pass);
/*insert code*/
connection.close();
System.out.println("It worked :)");
} catch (Exception e) {
System.out.println("Something went wrong :(");
e.printStackTrace();
}
}
I get an exception that there's no suitable driver. I'm not sure why because I have the jar downloaded and pathed correctly
Your connection should be a JDBC URL in the form
String url = "jdbc:mysql://mysql9.000webhost.com:3306/";
Now in order for this to work you should:
1) Verify that mySQL is running on the host mysql9.000webhost.com
2) Verify that the port is the default port ie 3306, if not change the code above to use the right port
String host should be like
String host = "jdbc:mysql:ip:port"//ip or hostname
example code that works for me...
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:1433;"
+"databaseName=test;"
+"user=sa;"
+"password=xxxxx;");
System.out.println("connected");
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.