I am trying to establish a connection but for some reason I am having issues doing so.
I think it may be a syntax error - but I am not completely sure. I have commented out numerous syntax approaches I have tried. I used MySQL documentation for help, even when following their syntax i get problems.
When I run the code without the Connection the program jumps into the try. But as soon as I add the Connection code it jumps to the catch section of the code - therefore there must be an issue with the syntax.
Can anyone spot where I have gone wrong? Thank You in advance.
public void selectData()
{
try
{
Connection con = null;
//Accessing driver from the JAR file
Class.forName("com.mysql.jdbc.Driver").newInstance();
//Class.forName("com.mysql.jdbc");
//String a = "jdbc:mysql://localhost:3306/c3361434?profileSQL=true";
///String a = "jdbc:mysql://address=(protocol=tcp)(host=localhost)(port=3306)(user=root)(password=root)/c3361434";
//Connection con = DriverManager.getConnection("jdbc:mysql://address=(protocol=tcp)(host=localhost)(port=3306)(user=root)/c3361434");
//Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/c3361434", "root", "root");
//con = DriverManager.getConnection("jdbc:mysql://localhost:3306/c3361434?" + "user=root&password=root");
Output3.setText("Connection has been established");
/*
PreparedStatement statement = con.prepareStatement("SELECT * FROM RSA-data");
ResultSet result = statement.executeQuery();
while(result.next())
{
Output2.setText(result.getString(1));
Output3.setText("in the while loop");
}
*/
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
Output4.setText("db fail");
}
}
try it:
Check if you mysql is running, in command line type:
mysqld --install
In java source:
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDB?dontTrackOpenResources=true");
the command mysqld not reconized because you need to enter at path specific.
For example:
MS - DOS:
cd C:/MySQL/bin
C:/MySQL/bin>mysqld --install
Into folder bin there is the mysqld.exe
Do you got it ?
Related
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.
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.
I created an application that writes data to the database every 5 minutes.
However after some time this error appears:
Error: Data source rejected establishment of connection, message from server: "Too many connections"
I've been searching around and tells you to close the connection to the database after every request side.
I tried this:
conexao.close();
But it gives me this error:
No operations allowed after conection closed.
I apologize if the question is not well formulated.
Thanks for the help
---------------------What I tried but didn't work---------------------------
Add
finally{
if(conexao!=null)
conexao.close();
}
Class.forName("com.mysql.jdbc.Driver");
Connection conexao = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/bdTeste", "root", "root");
Statement stm = conexao.createStatement();
BufferedReader reader = new BufferedReader(new FileReader("C:/Users/RPR1BRG/Desktop/test.txt"));
String dados[] = new String[6];
String linha = reader.readLine();
while (linha != null) {
StringTokenizer st = new StringTokenizer(linha, ";\"");
dados[0] = st.nextToken();
dados[1] = st.nextToken();
dados[2] = st.nextToken();
dados[3] = st.nextToken();
dados[4] = st.nextToken();
dados[5] = st.nextToken();
DateFormat dateFormat = new SimpleDateFormat("d-M-yy");
PreparedStatement stmt = (PreparedStatement) conexao.prepareStatement("replace into registos"
+ " (data_registo, hora_registo, IdSensor, Temperatura, Humidade, pt_orvalho) values (?,?,?,?,?,?)");
try {
stmt.setDate(1, new java.sql.Date(dateFormat.parse(dados[0]).getTime()));
stmt.setString(2, dados[1]);
stmt.setString(3, dados[2]);
stmt.setString(4, dados[3]);
stmt.setString(5, dados[4]);
stmt.setString(6, dados[5]);
} catch (java.text.ParseException ex) {
Exceptions.printStackTrace(ex);
}
stmt.executeUpdate();
linha = reader.readLine();
PrintWriter writer = new PrintWriter("C:/Users/RPR1BRG/Desktop/test.txt");
writer.print("");
writer.close();
Verifica();
}
} catch (ClassNotFoundException | SQLException | IOException e) {
System.err.println("Erro: " + e.getMessage());
}finally{
if(conexao!=null)
conexao.close();
}
This kind of problem arises when you are NOT properly closing the connection after usage.
Please use finally block after catch to close the connections appropriately. This is because to ensure that the connection gets closed properly even when there is an unexpected exception or error. Please note that statements inside finally block gets executed always. it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break
Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
As you have asked in comment, I have added the code sample to demonstrate practically!
Connection con = null
try{
//Establishing connection to datasource
con = DBConnection.getConnection();
//perform DB operations
...
...
...
}catch(SQLException sqlEx){
/*To catch any SQLException thrown during DB
*Operations and continue processing like sending alert to admin
*that exception occurred.
*/
}finally{
/*This block should be added to your code
* You need to release the resources like connections
*/
if(con!=null)
con.close();
}
Please note that the declaration of Connection variable should be in proper scope to close it in finally block.
Hope this helps!
This may be because of the configured max_connections is not suitable with the Connection Pool size set in JDBC or number of connections you open against DB.
to check number of max_connections in mysql:
show variables like 'max_connections';
make sure you have proper value of opened connections with the DB Max connections.
As from Java 7, java.sql.Connection is AutoCloseable. From now on, you can write your code like this:
try(Connection con = (Connection) DriverManager.getConnection(url, username, pazzword)) {
//your statements
}catch(RuntimeException e) {
}
Restart apache tomcat server will work. This worked for me.
Welcome
I found this example to connect with a SQLite database:
try{
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:C:\\pruebaSQLite\\dbTest.sqlite");
System.out.println("Conectado a la base de datos SQLite ");
}catch(Exception e){
System.out.println(e);
}
it's working fine but I try to connect a JAVA application using it like this:
try {
Class.forName("org.sqlite.JDBC");
Connection con = DriverManager.getConnection("jdbc:sqlite:C:\\LoginJava2\\myDB.sqlite");
PreparedStatement pstm = con.prepareStatement("insert into hell(username,pssword) " +
"values ('"+tfUname.getText()+"','"+tfUpass.getText()+"')");
pstm.close();
con.close();
JOptionPane.showMessageDialog(null,"Congrats, you have been registered succesfully");
RegisterWindow rw = new RegisterWindow();
rw.setVisible(false);
pack();
dispose();
} catch(SQLException ex) {
setTitle(ex.toString());
}
the line: "Class.forName("org.sqlite.JDBC");" give me the next error:
Unhandled exception type ClassNotFoundException
if I remove that line the program runs fine but when I execute the action, it gives me the next exception:
java.sql.SQLException: No suitable driver found for jdbc:sqlite:C:\\LoginJava2\\myDB.sqlite
That's weird because I'm using the same jar in both examples.
I'm using the next jar file: "sqlitejdbc-v056"
if someone could help me how to fix the error in the "line Class.forName("org.sqlite.JDBC");"
or if I'm doing someting wrong in the URL connection... I will apreciate!!
Thanks and sorry for my english!!
if someone clud help me how to fix the error in the "line Class.forName("org.sqlite.JDBC");" or if I'm doing someting wrong in the URL connection... I will apreciate!!
The error message is telling you exactly what needs to be fixed -- you need to handle the exception that it mentions, the ClassNotFoundException.
The main thing you should notice is that catch blocks in your two code examples are different, and one works while the other doesn't. Note that I don't recommend that you use the first catch block, the one that catches Exception, even though it works, since catching all Exceptions is usually not a good idea and prevents exceptions that should percolate to a higher level from doing so. Instead you should catch the explicit Exceptions that need to be caught, here SQLException and ClassNotFoundException.
The Exception Tutorial should help explain this more fully to you with code examples. How you catch this also will depend on if you're working with Java 1.7 or prior versions.
To Fix the problem I added the next to the code:
try {
Class.forName("org.sqlite.JDBC");
Connection con = DriverManager.getConnection("jdbc:sqlite:C:\\LoginJava2\\myDB.sqlite");
Statement com = con.createStatement();
com.executeUpdate("insert into hell(username,pssword) " +
"values ('"+tfUname.getText()+"','"+tfUpass.getText()+"')");
con.close();
JOptionPane.showMessageDialog(null,"Congrats, you have been registered succesfully");
RegisterWindow rw = new RegisterWindow();
rw.setVisible(false);
pack();
dispose();
} catch(SQLException ex) {
setTitle(ex.toString());
}
catch(ClassNotFoundException e) { // I added this catch to handle the exception
setTitle(e.toString());
}
Okay i know i have to use the JDBC etc, but im not sure how to implement the jar into my code, i have a basic code to open the file etc, but how can i actually incorporate the sqlite jar alongside my java class file to be run anywhere?
So for example i have a folder with:
Test.class
new.db
sqlite.jar
In Test.class i have the basic connection and imports:
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:new.db");
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT empname FROM employee");
while (resultSet.next()) {
System.out.println("EMPLOYEE NAME:"
+ resultSet.getString("empname"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
So how can i have this simple little script portable?
Thanks
Add the sqlite.jar to you classpath:
java -cp .;./sqlite.jar Anima
This should work. If not - please show your error message.
Edit
tested and verified. Create/Have a folder with the following content:
./project
Anima.class
sqlite.jar
then cd to folder project and do a
java -cp .;./sqlite.jar Anima
It works as expected on my machine.