I am using android studio to develop an application and using Azure Sql Server to host my database. The problem is I was able to connect to my database on SQL server but it has an error of Object not found in my database.
I found out that it might be connecting to my master database instead of the database I want it to connect to. Is there any solution to solve the problem?
package com.example.lenovo.testing1;
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.*;
public class ConnectionClass {
String hostName = "haozailai.database.windows.net";
String dbName = "haozailai";
String user = "username";
String password = "password";
#SuppressLint("NewApi")
public Connection CONN() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String ConnURL;
Connection conn = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = String.format("jdbc:jtds:sqlserver://haozailai.database.windows.net:1433;database=haozailai;user=username;password=password;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
conn = DriverManager.getConnection(url);
}catch (SQLException se)
{
Log.e("error here 1 : ", se.getMessage());
}
catch (ClassNotFoundException e)
{
Log.e("error here 2 : ", e.getMessage());
}
catch (Exception e)
{
Log.e("error here 3 : ", e.getMessage());
}
return conn;
}
}
Picture of my database structure
I tried to connect my sqlserver via java jdbc and did not reproduce your issue.
I can connect to my application db successfully.
My test code:
import java.sql.*;
public class Test {
public static final String url = "jdbc:sqlserver://***.database.windows.net:1433;database=***;user=***password=***;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
public static final String name = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
public static Connection conn = null;
public static PreparedStatement pst = null;
public static Statement stmt = null;
public static ResultSet rs = null;
public static void main(String[] args) {
try {
String SQL = "select * from dbo.Student";
Class.forName(name);
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("name"));
}
close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close() {
try {
conn.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
After some research, I found out it is because of your connect url.
You need to modify your connect url :
jdbc:jtds:sqlserver://haozailai.database.windows.net:1433/<your application db name> ...
You could refer to the pages below for more details.
https://sourceforge.net/p/jtds/discussion/104389/thread/a672d758/
how to connect sql server using JTDS driver in Android
Update answer:
I have made a slight adjustment to your connect URL and can connect to my application database normally.
try {
String SQL = "select * from dbo.Student";
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String url = String.format("jdbc:jtds:sqlserver://***.database.windows.net:1433/<your database name>;user=***;password=***;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("name"));
}
close();
} catch (Exception e) {
e.printStackTrace();
}
Notice that remove the database=*** and add "/<your database name>" after your host string.
Please refer to the above code and try again.Any concern, please let me know.
Hope it helps you.
I know this answer is waay too late, but I found this video that totally works: https://www.youtube.com/watch?v=WJBs0zKGqH0
The thing is, you have to download a jtds jar, the guy in the video says where you can get it from and also, you need to add "jtds" before "sqlserver" in connection url and edit the way the 'databe' is written in the connection url, like this:
jdbc:jtds:sqlserver://serverName.database.windows.net:portNr:DatabaseName=dbName;user=....
Related
I've got a mysql question within java. I've got a mysql database with different tables. I currently got a database called 'litebans' and a table called 'litebans_mutes'.
Within that table there is a row called reason and under that reason (let's say what's within reason) there's a string called 'This is a test' and 'sorry'; how would I get the string 'This is a test' and 'sorry' associated with the same 'uuid' row in java? Here is a picture explaining more:
Here is an image explaining the sql format
Additionally, i've currently initialized all variables and such in java, i currently have this code:
http://hastebin.com/odumaqazok.java (Main class; using it for a minecraft plugin)
The below code is the MySQL class; api used to connect and execute stuff.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.octopusmc.punish.Core;
public class MySQL {
public static Connection openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
System.err.println(e1);
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://" + Core.host + ":" + Core.port + "/" + Core.database, Core.user, Core.pass);
System.out.println("Currently connected to the database.");
return conn;
} catch (SQLException e) {
System.out.println("An error has occured while connecting to the database");
System.err.println(e);
e.printStackTrace();
}
return null;
}
public static void Update(String qry) {
try {
Statement stmt = Core.SQLConn.createStatement();
stmt.executeUpdate(qry);
stmt.close();
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
}
public static Connection getConnection() {
return Core.SQLConn;
}
public static ResultSet Query(String qry) {
ResultSet rs = null;
try {
Statement stmt = Core.SQLConn.createStatement();
rs = stmt.executeQuery(qry);
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
return rs;
}
}
An example using that api above is shown below:
try {
ResultSet rs = MySQL.Query("QUERY GOES HERE");
while (rs.next()) {
//do stuff
}
} catch (Exception err) {
System.err.println(err);
err.printStackTrace();
}
tl;dr: I want to get the two fields called 'reason' with the give 'uuid' string field.
First , make sure that your using the jdbc mysql driver to connect to the database
Defile a class where you could write the required connection and create statement code.
For example
class ConnectorAndSQLStatement {
ResultSet rs = null;
public Statement st = null;
public Connection conn = null;
public connect() {
try {
final String driver = "com.mysql.jdbc.Driver";
final String db_url = "jdbc:mysql://localhost:3306/your_db_name";
Class.forName(driver);//Loading jdbc Driver
conn = DriverManager.getConnection(db_url, "username", "password");
st = conn.createStatement();
rs = st.executeQuery("Select what_you_want from your_table_name");
while (rs.next()) {
String whatever = rs.getInt("whatever ");
System.out.print(whatever);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Just call this function and the magic :D
Hope it is helpful
package WBSer_RwCnt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Rw_Count {
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/hospital_data";
String username = "root";
String password = "mysql";
Class.forName(driver); // load MySQL driver
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static int countRows(Connection conn, String tableName) throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
} finally {
rs.close();
stmt.close();
}
return rowCount;
}
public static void main(String[] args) {
Connection conn = null;
try {
conn = getConnection();
String tableName = "hospital_status";
System.out.println("tableName=" + tableName);
System.out.println("conn=" + conn);
System.out.println("rowCount=" + countRows(conn, tableName));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
// release database resources
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Error --->
The method "getConnection" on the service class "WBSer_RwCnt.Rw_Count" uses a data type, "java.sql.Connection", that is not supported
When i compile it without creating it as webservice it works correctly
but when i make it as web service it gives output as
Output --->
WBSer_RwCnt.Rw_CountSoapBindingStub#121a412b
Please Help !
Next Try
So this is what i have done after what you have said even then it gives following errors
Exception:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/hospital_data
Message:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/hospital_data
package WBSer_RwCnt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Rw_Count {
public static int countRows() throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
System.out.println("ram");
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/hospital_data";
String username = "root";
String password = "mysql";
try {
Class.forName(driver);
}
catch (ClassNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
// load MySQL driver
Connection conn = DriverManager.getConnection(url, username, password);
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM hospital_status");
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
finally {
rs.close();
stmt.close();
conn.close();
}
return rowCount;
}
}
i have the added all jar files including the java mysql connectors
This is not going to be a full answer as I'm not exactly sure about the tools you are using to compile the web service, but anyway, here goes:
Basically, a connection is something that is only valid on a particular machine. If it's a TCP/IP connection, it consists of two pairs: source host and port, and target host and port. If it's a Linux socket, then it is an entry in that particular machine's directory tree.
A database connection is usually built on one of those constructs, so it, too, is particular to a machine.
Therefore, it doesn't make sense to pass a Connection object to the user who calls your method from some remote machine. And since it doesn't make sense, the JAX-RPC standard does not include a serialization for Connection, and that's why it fails.
Your problem is that you have designed your method such that it accepts a connection as a parameter, and uses that connection to access the database. This works OK locally, but is not a good design for a remote service.
Instead, your method should acquire the connection internally. The remote user should access just the countRows method, with the name of the table, and countRows should call getConnection, use the connection, and the close it.
You shouldn't have a main method in a web service. And the getConnection method should be changed from public to private, so that countRows can access it. When it is private, I believe the web service compiler will not complain about it because it doesn't have to create a serialization for it.
I'm trying to teach myself how to connect to a msaccess database in java.
I have set up a class to access the database as follows
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public abstract class AccessDBConnect2 {
public static Connection connect(){
String fileName = "C:/Users/Bridget/Documents/EmployeeSys.accdb";
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+fileName;
con = DriverManager.getConnection(url,"","");
} catch (Exception e) {
// Handle exceptions ...
System.out.println(e.toString());
System.out.println("A problem accessing the database");
e.printStackTrace();
} finally {
try { if(con!=null) {con.close();} } catch (Exception e) {}
}
return con;
}
public static void closeConnection(Connection conn){
try{
conn.close();
}catch (Exception e){
}
}
Then I have my code which is just trying to select everything from the table.
I have created the table in msAccess and the code seems to get through the connect method in the above code without any problems, indicating it is finding the database and accessing it somewhat. The problem happens when I call the prepareStatement using the connection, i.e. code line:
stm = conn.prepareStatement(sql);
The full code is:
import java.sql.*;
public class Program2{
public static void main(String[] args) {
try{
// Load the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
// Establishing db connection
Connection conn = AccessDBConnect.connect();
// Displaying all records from employee file
System.out.println("Display records of all employees");
display(conn);
// Closing the connection
AccessDBConnect.closeConnection(conn);
}catch (Exception e){
System.out.println("Error");
}
}
// Display details of all employees
public static void display(Connection conn){
PreparedStatement stm = null;
// SQL statement
String sql = "SELECT * FROM Employee";
ResultSet rs;
try {
stm = conn.prepareStatement(sql); // Prepare the SQL statement
rs = stm.executeQuery(); // Execture the SQL statement
// Navigate through the ResultSet and print
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
String address = rs.getString("address");
System.out.println("ID: \t \t" + id);
System.out.println("Name: \t \t" + name);
System.out.println("Gender: \t" + gender);
System.out.println("Address: \t" + address);
System.out.println(" ");
}
// Closing the resultSet
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void test(){
int a = "hello";
}
}
You are receiving the error because when you try to call .prepareStatement the connection is closed. Your AccessDBConnect2 class contains a finally block that closes the connection before it returns. Fix that class so it leaves the connection open.
By the way, the JDBC-ODBC Bridge has been removed from Java 8 and is effectively obsolete. You might be interested in this alternative:
Manipulating an Access database from Java without ODBC
I've removed the obviously incorrect answer :) another possibility:
I would think the issue is in your connection to the database, try changing 'C:/Users/Bridget/Documents/EmployeeSys.accdb' to 'C:\\Users\Bridget\Documents\EmployeeSys.accdb'
I am getting error when I try to connect database
Error:com.microsoft.sqlserver.jdbc.SQLServerConnection cannot be cast to
Ptakip.Connection
Ptakip is my Package
Connection is my Class
Here is the Connection Class Code ;
import java.sql.*;
public class Connection {
private Connection cn;
public Connection connector( )
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:sqlserver://localhost\\MyServer:
1433;databaseName=TEST;user=Glassfish;password=pass;");
System.out.println("connected");
}
catch(Exception ex) {
System.out.println("Error:" + ex.getMessage());
System.out.println(cn);
}
return cn;
}
}
your class has the same name as the class in the package java.sql that's why u have this conflict ,juste try to change the name to Connexion ,it should work
Try to make a connection like this. it may help you
String url = "jdbc:mysql://localhost:3306/";
String dbName = "demo”
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "mypasswd";
try {
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url+dbName,userName,password);
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
I can connect from plsql to database using tns file
Now I want to connect to the database from my Java using JDBC.
What I tried:
I search google and I find that I have to using this connection String:
"jdbc:oracle:thin:#//host:port))/tnsfile)";
My computer name is myPC
The port that is written in the tnsfile is 5151
So I tried this connection String
"jdbc:oracle:thin:#//myPC:5151))/tnsfile"
but I got this Exception
java.sql.SQLRecoverableException: IO ERROR: SO Exception was generated
What am I doing wrong?
How to connect my JDBC to the database using tns file?
You have to set a property named oracle.net.tns_admin to point to the location of the folder containing your tnsnames.ora file. Then you specify the entry from that file after the # sign in your DB URL. Check example below. You can find more information here: Data sources and URLs - Oracle Documentation
import java.sql.*;
public class Main {
public static void main(String[] args) throws Exception {
System.setProperty("oracle.net.tns_admin", "C:/app/product/11.2.0/client_1/NETWORK/ADMIN");
String dbURL = "jdbc:oracle:thin:#ENTRY_FROM_TNSNAMES";
Class.forName ("oracle.jdbc.OracleDriver");
Connection conn = null;
Statement stmt = null;
try {
conn = DriverManager.getConnection(dbURL, "your_user_name", "your_password");
System.out.println("Connection established");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT dummy FROM dual");
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (stmt != null) try { stmt.close(); } catch (Exception e) {}
if (conn != null) try { conn.close(); } catch (Exception e) {}
}
}
}
Example entry from tnsnames.ora file:
my_net_service_name=
(DESCRIPTION=
(ADDRESS=(some address here))
(CONNECT_DATA=
(SID=some_SID_name)))
Where my_net_service_name string is what you have to subsitite for ENTRY_FROM_TNSNAMES from my Java example.
Rather than hard code the path to tnsnames.ora, better to find it from the environment:
public static void setTnsAdmin() {
String tnsAdmin = System.getenv("TNS_ADMIN");
if (tnsAdmin == null) {
String oracleHome = System.getenv("ORACLE_HOME");
if (oracleHome == null) {
return; //failed to find any useful env variables
}
tnsAdmin = oracleHome + File.separatorChar + "network" + File.separatorChar + "admin";
}
System.setProperty("oracle.net.tns_admin", tnsAdmin);
}
Try the following:
System.setProperty("oracle.net.tns_admin", PATH_TO_TNSNAMES.ORA);
Class.forName ("oracle.jdbc.OracleDriver");
dbUrl = "jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST="+IPHOST+")(PORT="+PORT+"))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME="+DBNAME+")))"
conn = DriverManager.getConnection(dbUrl, USERNAME, PASSWORD);
Be sure to have the latest version of ojdbc.jar