Cannot connect to MS Database with java - java

When attempting to open a connection to a database it fails giving me a NullPointerException. This happens when it is trying to get the connection on the con = DriverManager.getConnection(url); line. It goes from this line to the catch exception. What is the correct way?
public void openDatabase () {
url = "jdbc:odbc:student";
try{
con = DriverManager.getConnection(url);
stmt = con.createStatement();
txtOutput.setText("Database " + url + " is connected\n");
}
catch (Exception e) {
txtOutput.setText("Problems connecting to " + url + "\n");
}
}

Related

Different images inserted from Android into database shows same value?

I am trying to insert image into SQL Server here is my code and it works perfectly (it inserts image into database). My problem starts after insertion and when I see the image column in database.
protected String doInBackground(String... strings) {
try {
con = connectionClass(ConnectionClass.un, ConnectionClass.pass, ConnectionClass.db, ConnectionClass.ip);
if (con == null) {
z = "No Internet Connection";
} else {
String sql = "INSERT INTO [dbo].[tblComplaint] (customerName,type,image) VALUES ('" + name.getText() + "','" + complain.getText() + "','" +encodedImage+"')";
//PreparedStatement stmt = con.prepareStatement(sql);
//stmt.executeUpdate();
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
}
} catch (Exception e) {
isSuccess = false;
z = e.getMessage();
}
return z;
}
#SuppressLint("NewApi")
public Connection connectionClass(String user, String password, String database, String server) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String connectionURL = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connectionURL = "jdbc:jtds:sqlserver://" + server + "/" + database + ";user=" + user + ";password=" + password + ";";
connection = DriverManager.getConnection(connectionURL);
} catch (Exception e) {
Log.e("SQL Connection Error : ", e.getMessage());
}
return connection;
}
Problem: No matter what image I sent into database, it only inserts the same set of strings starting with: 0x2F396A2F34414151536B5A4A5267414241514141415141424141442F3467496F53554E44583142 and it goes on for a 100s lines, which I am guessing is not right. I have tried send 4-5 different images but this does not change. What am I doing wrong? Data type for image column is image, I have also tried varbinary(max) and so on.

Retry JDBC connection in Java

I am trying to have a retry logic for getting JDBC connection in case I get SQL Exception with something like :
int counter = 0;
Connection conn = null;
while (null == conn) {
try {
conn = GetConnectionObject;
} catch (SQLException e) {
if (++counter > MAX_RETRY) {
//Log ERROR
break;
}
} finally {
if (null != conn) {
try {
DbUtils.close(conn);
} catch (SQLException e) {
logger.error("Exception while closing the connection object");
}
}
}
}
I cannot test this currently hence need some help.
This will work fine if I get exception and then I can log after retrying. But if we DO NOT get exception, it will come to the finally block and close the connection. Try-Catch-Finally are inside while loop.
So If I close my connection, flow if reach
while( null== conn)
Will my connection object become null after closing ?
Or If there is some other way around to implement retry part ?
No, it won't become null after closing. Use Connection.isClosed() instead of while( null== conn). Also, you should get //Do some task. out of this code since it's goal is to get a JDBC connection.
Here is the tested method for your problem. This method tries 3 times for the connection and when it will get the DB connection it will Print Success message and will run the query and display the result otherwise it will print the error message. Also if the connection is successful then it will close the connection after executing query in finally block.
public void retryDBConnection(){
int counter = 0;
Connection con = null;
while(counter < 3 && con == null){
try{
String str = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(str).newInstance();
con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;Database=TestDB;", "sa", "sqldb");
System.out.println("DB Connection Successful!");
PreparedStatement prep = con.prepareStatement("select ID, User_Name from tblUser where ID = 9");
ResultSet rs = prep.executeQuery();
if(rs.next()){
System.out.println("User ID = " + rs.getString(1));
//name = rs.getString(2);
}
}
catch(SQLException e){
// System.out.println(e.getSQLState());
if(e.getErrorCode() == 0 || e.getErrorCode() == 4060)
counter++;
System.out.println("Attempt: " + counter +", Could not establish DB Connection!");
System.out.println("Error Code: " + e.getErrorCode());
}
catch(Exception e){
e.printStackTrace();
}finally{
if(con != null){
try {
con.close();
System.out.println("Connection closed...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
Here is the out put of the method.
Attempt: 1, Could not establish DB Connection! Error Code: 0 Attempt: 2, Could not establish DB Connection! Error Code: 4060 DB
Connection Successful! User ID = 9 Connection closed...

JDBC returning empty result set on server

I've got a little problem when I'm running my query.
This is my code:
try {
// Class.forName("com.mysql.jdbc.Driver");
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
} catch (Exception ex) {
// handle the error
System.out.println("Driver issue: " + ex.getMessage());
System.out.println("Driver issue: " + ex.getClass().toString());
}
try {
// Do something with the Connection
System.out.println("Connection: " + conn);
Statement stmt = conn.createStatement();
ResultSet RS = stmt.executeQuery("show slave status");
...
try {
conn = DriverManager.getConnection("jdbc:mysql://" + internetPort + ":" + port + "/", username, password);
System.out.println("Connected to: " + internetPort);
return;
} catch (SQLException e) {
I realized that the script is connecting to DB, then execute query but the result is empty. When I'm doing the same query on mysql console then I got 1 result (correct result) I've even changed query "show slave status" to "show processlist" and still nothing. What's more, on my PC it's working correctly and executing query with correct result, but on other PC it doesn't. user and password is correct (the same i logged in console). Could anyone help me with that?

Connecting MS Access Database with my project

I m trying to execute this code & it shows successfull execution but i cant get any value n access database file which i had create.
so, please find mistake in my code so that i can get some values in database table.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String filename ="D:\\Database for Mini Project\\Database21(example).mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:\\Database for Mini Project\\Database21(example).mdb";
try (Connection con = DriverManager.getConnection( database ,"","")) {
Statement s = con.createStatement();
String b=request.getParameter("uname");
String c=request.getParameter("pass");
String query="insert into A.ABC1(uname,pass) values='"+b+"','"+c+"'";
s.executeQuery(query);
s.close();
change s.executeQuery(query); to s.executeUpdate(query);
For data manipulation language use executeQuery(); as mentioned in oracle docs
Try this
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String filename ="D:\\Database for Mini Project\\Database21(example).mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:\\Database for Mini Project\\Database21(example).mdb";
String b=request.getParameter("uname");
String c=request.getParameter("pass");
try {
// connects to the database
Connection con = DriverManager.getConnection( database ,"","")) {
Statement s = con.createStatement();
String query="insert into A.ABC1(uname,pass) values(?,?);
PreparedStatement statement = conn.prepareStatement(query);
s.setString(1, b);
s.setString(2, c);
int row = s.executeUpdate();
if (row > 0) {
message = "Query executed";
}
} catch (SQLException ex) { //catch ur msaccess exception..I use mysql
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (con != null) {
// closes the database connection
try {
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
I use mysql as my database..so wherever there is catch(SQLException ex) replace it with msaccess exception..

Java connection to database

I have exhausted all avenues to sort out this problem, but to no avail. I have installed "SQL Management Studio 2012" and created a dummy database and methods, but I'm still getting a "null point exception pointer". Java and JDBC is set under user variables.
Here are the screen shots and code.
Static {
// standard code to open a connection and statement to SQL Server database
try {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://SQL-SERVER;"
+ "databaseName=ItunesDB;integratedSecurity=true;";
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
} // Handle any errors that may have occurred.
catch (SQLException sqle) {
System.out.println("Sql Exception :" + sqle.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found Exception :" + e.getMessage());
}
}
public static String listAll() {
String output = "";
try {
stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable");
while (res.next()) { // there is a result
// the name field is the thrid one in the ResultSet
// Note that with ResultSet we count the fields starting from 1
output += res.getString(1) + " " + res.getString(2) + " - "
+ res.getString(3) + " " + res.getString(4) + " "
+ res.getString(5) + "\n";
}
} catch (Exception e) {
System.out.println(e);
return null;
}
return output;
}
public static String getName(String key) {
try {
SELECT * FROM LibraryTable WHERE key = '04'
stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM LibraryTable WHERE ID = '" + key + "'");
if (res.next()) { // there is a result
// the name field is the second one in the ResultSet
// Note that with ResultSet we count the fields starting from 1
return res.getString(2);
} else {
return null;
}
} catch (Exception e) {
System.out.println(e);
return null;
}`enter code here`
The database information:
Dummy Database
ID Name Artist Quantity Price Rating Playcount
What do I need to do to fix this?
Re install sql server in mixed mode . Then go to SQL Server configuration manager and checks is the TCP/Ip is enable . IF not enable it and restart the service. Then add sqljdbc jar in your project . Then try this code
Connection con = null;
try {
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;"
+ "user=sa;password=HerongYang;"
+ "database=AdventureWorksLT");
}
user is always sa because it is the system administrator

Categories