About JDBC Connection - java

A very simple question but i'm newbie in Java. How can I do the connection with my SQL Server DataBase that are in my network ?
I made the download of the JDBC 4.0, associate the file in my project and I'm trying the follow code, but I don't know how can I do a reference to my database
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "what i put here ?";
Connection con = DriverManager.getConnection(connectionUrl, "sa", "testtest");
} catch (SQLException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}

String url = "jdbc:mysql://localhost:3306/";
String db = "yourDB";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
try {
Class.forName(driver);
Connection con = DriverManager.getConnection(url + db, user, pass);
con.setAutoCommit(true);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}

try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
DriverManager.getConnection("jdbc:sqlserver://url.com;database=dbname;user=username;password=test")
} catch (SQLException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
replace the url/username/password. This is the connectionstring for sql server

Related

Why don't work on the device and work on the simulator?

I'm making an app that access a mysql DB. I'm using direct JDBC, not web service. The simulator access with no problem but the real device give the error
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
This is the code of the connection class (its only the connection method)
public static Connection CONN(String name) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classs);
conn = DriverManager.getConnection(url, un, password);
String stsql = "Select version()";
Toaster.toast(name);
//conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
Toaster.toast(se.getMessage());
System.out.println( se.getMessage() );
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}
Can someone gives me some help?
Thanks!

i want to connect to db on java, but there is some errors

package dbb;
import java.sql.*;
public class test {
public static void main (String[] args) {
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String pass = "1234";
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Searched");
conn = DriverManager.getConnection(url, user, pass);
System.out.println("Connection Succeed" + conn);
} catch (ClassNotFoundException e) {
System.out.println("Driver Not Searched");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
i made this code on java, but there are some errors.
for example,
.
It shows that Driver is already searched, but the connection is still failed.
How can i fix the error?
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String pass = "Admin#123";
java.sql.Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Searched");
conn = DriverManager.getConnection(url, user, pass);
System.out.println("Connection Succeed" + conn);
} catch (ClassNotFoundException e) {
System.out.println("Driver Not Searched");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
it's working fine in my system with mysql-connector-java-5.1.6jar. Might be This is an issue with the MySql driver.
You can try with below :
you might need to explicitly specify timezone in you jdbc url.:
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
As already suggested in the comment to use non-ssl connection with latest driver, you should use below code:
package dbb;
import java.sql.*;
public class test {
public static void main (String[] args) {
String url = "jdbc:mysql://localhost:3306/test?useSSL=false";
String user = "root";
String pass = "1234";
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver Searched");
conn = DriverManager.getConnection(url, user, pass);
System.out.println("Connection Succeed" + conn);
} catch (ClassNotFoundException e) {
System.out.println("Driver Not Searched");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

DB connection pooling in Neo4j jdbc driver

In my application I'm using neo4j-community-2.3.0-M02 with neo4j-jdbc 2.3.2 . It creates large number of threads each should execute 3 or 4 cypher queries. To execute queries I use following method,
private ResultSet executeCypher(String queryString) throws Exception {
try {
String restUrl = getPropertiesCache().getCofigProperty("neo4j_url");
String driver = getPropertiesCache().getCofigProperty("neo4j_driver");
String userName = getPropertiesCache().getCofigProperty("neo4j_user");
String passWord = getPropertiesCache().getCofigProperty("neo4j_pwd");
Class.forName(driver);
try{
Neo4jConnection connection = (Neo4jConnection)
DriverManager.getConnection(restUrl, userName, passWord);
try {
PreparedStatement stmt = connection.prepareStatement(queryString);
try{
ResultSet rs = (ResultSet) stmt.executeQuery(queryString);
stmt.close();
connection.close();
return rs;
}catch (SQLException e){
e.printStackTrace();
} catch (NullPointerException e1){
e1.printStackTrace();
} catch (RuntimeException e2){
e2.printStackTrace();
}
if(!stmt.isClosed()){
stmt.close();
}
}catch (Exception e){
e.printStackTrace();
}
if(!connection.isClosed()){
connection.close();
}
}catch (Exception e){
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Which means I'm creating db connection for each cypher query. I think it's very bad idea because when creating large number of connections most of them start to be timeout. I think db connection pooling will help on this case or is there any better idea regarding this than connection pool?
If connection pooling solve this issue, please give an example of how to create db connection pool using neo4j jdbc driver.
The neo4j-jdbc 2.3X driver uses the REST API to connect to the database, basically they are http calls using Restlet API, so there is no connection being opened or closed when you create/close JDBC connections.

Google cloud platform returning no content

Im making a REST Api using JAX RS and Google Cloud Platform, however when i test the api I get HTTP204 no content returned, I think it could be to do with my database connection but no matter what I change it doesnt fix it
#Override
public Response getAllStaff() {
ArrayList<StaffInfo> staffArray = new ArrayList<>();
Response response = null;
String url = null;
try {
if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
Class.forName("com.mysql.jdbc.GoogleDriver").newInstance();
url = "jdbc:google:mysql://{project-id}:staff-database/staffDatabase";
}
// Connection conn = DriverManager.getConnection(
// "jdbc:google:mysql://your-project-id:your-instance- name/database",
// "user", "password");
Connection conn = DriverManager.getConnection(url, "michael", "password");
Statement st = conn.createStatement();
String sql = ("SELECT * FROM StaffTable;");
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
staffArray.add(new StaffInfo(rs.getInt(0),
rs.getString(1),
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5)));
}
GenericEntity<ArrayList<StaffInfo>> entity =
new GenericEntity<ArrayList<StaffInfo>>(staffArray) {};
response = Response.ok(entity).build();
// response = Response.ok(entity, MediaType)
conn.close();
} catch (ClassNotFoundException e) {
// Could not find the database driver
} catch (SQLException e) {
// Could not connect to the database
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
I get no error messages just that there is no content returned
Here is what i see on cloud platform sql
and when i click on "staff-database"
Make sure the IP address of the machine from which you are making the call is authorized. You will find it in the "Access Control" tab of Cloud SQL.

Unable to reopen MySQL connection in Java

I've got an annoying bug in Java. I'm connecting to a MySQL database and using Tomcat in Eclipse. It works brilliantly, but only the first time around. If I reload the page or run the page again, I get a com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
This is my code:
Connection conn = null;
String returnString = null;
Response response = null;
ResultSet rs = null;
try {
System.out.println("Trying to connect");
conn = DbUtil.getConnection(); // Connect to the database
System.out.println("Okay, connected");
query = conn.prepareStatement("SELECT host_firstname FROM host"); //Crashes at this line!
rs = query.executeQuery();
ConvertToJson jsonConverter = new ConvertToJson();
JSONArray jsonArray = new JSONArray();
jsonArray = jsonConverter.convertToJsonArray(rs);
returnString = jsonArray.toString();
response = Response.ok(returnString).build();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("hello!!!!");
}
finally {
if (rs != null){
rs.close();
}
if (query != null) {
query.close();
}
if (conn != null) {
conn.close();
}
}
return response;
I've seen everywhere I've Googled that I have to close the result set, the prepared statement and the connection (in that order) but once I've closed the connection, I can't reopen it.
This is my DbUtil class:
private static Connection connection = null;
public static Connection getConnection() {
if (connection != null) {
return connection;
}
else {
try {
Properties prop = new Properties();
InputStream inputStream = DbUtil.class.getClassLoader().getResourceAsStream("/db.properties");
prop.load(inputStream);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String user = prop.getProperty("user");
String password = prop.getProperty("password");
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return connection;
}
Any idea what is causing this problem?
Thanks
Omar :)
This answer is just to get your code working. But the best way would be to configure a connection pool. You should look about it.
YOur condition is :
if (connection != null) {
return connection; It's returning a closed connection
}
Try changing it to:
if (connection != null && !connection.isClosed()) {
return connection;
}

Categories

Resources