How can I connect a JDBC azure sql server to android application? - java

I have been writing an android application in android studio that needs access to a cloud database. I am using Microsoft Azure for my database and have already created it, however I am struggling to query it from the android application. When trying from Android Studio, I get an error to do with JDBC not being found, however I have tried adding the relevant .jar files with no luck. I have also tried creating a maven project as suggested on the Azure site, and with this I can access the database fine, however as soon as I try using the package created by maven as a module in Android Studio, the sql query no longer works and instead goes to the exception. Below you can see the function I am trying to access in the maven project:
public static ArrayList<Double[]> getIncidentDetails() {
// Connect to database
String url = "jdbc:sqlserver://............"; //Take ............ to be my connection string
Connection connection = null;
ArrayList<Double[]> results = new ArrayList<Double[]>();
try {
connection = DriverManager.getConnection(url);
System.out.println("Connected");
String selectSQL = "SELECT [latitude], [longitude]" + "FROM [Incidents]";
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(selectSQL)) {
while (resultSet.next()) {
System.out.println(resultSet.getString(2));
Double latitude = Double.parseDouble(resultSet.getString(1));
Double longitude = Double.parseDouble(resultSet.getString(2));
results.add(new Double[] {latitude, longitude});
}
connection.close();
}
} catch (Exception e){
System.out.println(e.getMessage());
}
return results;
}
Any ideas on how I could connect to the database from Android Studio, with or without the Maven project would be greatly appreciated.

Try to load the class before you open the connection:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);

Related

Java eclipse program, could not connect to MySQL

I am new to google cloud, and I just configure all components needed in cloud computation. But I have a problem on MySQL connection between MySQL and APP engine/VM. I can browser see my main html page, but when my servlet try to make MySQL connection and it failed.
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://mysql external IP:3306/Database?user=us&password=pw");
Error message: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure and The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Class.forName("com.mysql.jdbc.GoogleDriver");
con = DriverManager.getConnection("jdbc:google:mysql://mysql external IP:3306/Database?user=us&password=pw");
Error message: java.lang.ClassNotFoundException: com.mysql.jdbc.GoogleDriver at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
I add appengine-web.xml in WEB-INF folder with true
Does anyone have the solution on this? I deploy to google cloud from my local Eclipse 2020-06 version.
Thanks
You an try this sample code:
String url = "jdbc:mysql://ip:3306/dbname?useSSL=false";
String user = "root";
String password = "password";
StringBuffer datStr = new StringBuffer("");
String query = "SELECT * FROM dbname.tablename";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
//Code
}
} catch (Exception ex) {
ex.printStackTrace();
}

Android Studio Connection with the database on physical device via XAMPP

I'm writing an app, which connects to the database, and sends a basic query. Till now I did all my tests on Android Studio Emulator and it worked fine, until I tried it on my phone, which can't connect to the database.
try{
String myUrl = "jdbc:mysql://192.168.0.12/mydb";
miastoItemList =new ArrayList<>();
Connection c = DriverManager.getConnection(myUrl, "root",
"test");
Statement statement = c.createStatement();
String s = "SELECT * FROM city";
ResultSet rs = statement.executeQuery(s);
}

How to execute sql script in java for desktop apps

I have developed java desktop application where I have a class to create MySQL database and execute SQL script in it. Actually my script is in java package i.e. com.scriptrunner/myscript.sql. When I executed script which is in local drive like c:\myscript.sql, it works fine, but I could not find the solution to read a SQL script from project package and execute it. I have used iBatis ScriptRunner for running this script. Can desktop application read sql script from package and execute it ?
Thank you.
We can execute sql script which is in our package by this code. We need to add ibatis-sqlmap-2.3.0.jar in our library. This code first creates database myDb, then locates the path of script file i.e. in com.command.sql package and finally runs script into myDb database.
String dbName = "myDb";
String jdbcDriver = "com.mysql.jdbc.Driver"
//Created new database myDb.
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=")) {
Statement s = conn.createStatement();
int Result = s.executeUpdate("CREATE DATABASE IF NOT EXISTS "+dbName);
}
//This is the path to database; i.e. in com.command.sql package.
String scriptFilePath = "src\\com.command.sql\\mydatabase.sql";
// Create MySql Connection
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/"+dbName, "root", "root");
Statement stmt = null;
Class.forName(jdbcDriver);
try {
// Initialize object for ScripRunner
ScriptRunner sr = new ScriptRunner(con, false, false);
// Give the input file to Reader
Reader reader = new BufferedReader(new FileReader(scriptFilePath ));
// Exctute script
sr.runScript(reader);
} catch (IOException | SQLException e) {
System.err.println("Failed to Execute" + scriptFilePath
+ " The error is " + e.getMessage());
}

Issue while retrieving data from the mySQL database in AIX system

I am trying to retrieve data from MySQL database table. To do that, I use following code on various platforms. My code works perfectly on Windows and Linux platforms. But when I use same code in AIX 6.1, it does not retrieve correct data.
The Main Function:
String storedstring = objDBUtil.lookup(0);
logger.info(storedstring);
The Database Util Function:
public String lookup(String number) throws Exception {
String sql = "SELECT info FROM records WHERE Snumber=?";
Connection dbConn = connect();
try {
PreparedStatement stmt = dbConn.prepareStatement(sql);
try {
stmt.setString(1, number);
ResultSet rs = stmt.executeQuery();
try {
if (!rs.next()) {
throw new TException("does not exist in the database");
}
return rs.getString(1);
} catch (Exception e) {
logger.info("Unexpected exception caught during auth: " + e.getClass().toString() + " " + e.getMessage());
return null;
}finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
dbConn.close();
}
}
Output of the main function on Windows, I get the entire string from the database. But exact code gives me encrypted value on AIX machine.
Output on AIX machine [B#62637268
I resolved the issue. Issue was with connector file. I was using older version of connector file.
MySQL version I was using:
mysql-5.5.2-m2-aix5.3-powerpc-64bit
Non working version of Mysql connector with above mysql:
mysql-connector-java-3.1.7-bin.jar
Working version of MySQL connctor with above mysql:
New version: mysql-connector-java-5.1.6-bin.jar
Thank you everyone for looking into my question and trying to help me. Really appreciated.

Connecting a Microsoft Access Database to Java using JDBC and compiling

for a school database project we are making a database program (user GUI and the database). Using Microsoft Access 2010 I created the database and populated it with some sample data, and saved it in .mdb format and placed it in my project folder.
When running it in eclipse the following code works fine, connects and even retrieves the query. However I find that I am unable to export the code to a jar and run it (which is required for the project, give them a working copy of your program on a CD or flash drive), and I'm also unable to port the code over to Netbeans to have it work, as well as trying to compile on a Linux machine.
I assume this is a problem with including drivers or trying to use Microsoft access. The error I get when running the jar or running on Netbeans is given below the code. So I ask either how do I include drivers to make the program portable, or how else can I approach this problem?
Thanks in advance
import java.sql.*;
public class JDBCTest {
static Connection connection;
static Statement statement;
public static void main(String args[]){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=TLDATABASEDBM.mdb";
connection = DriverManager.getConnection( database ,"","");
buildStatement();
executeQuery();
}catch(Exception e){
e.printStackTrace();
System.out.println("Error!");
}
}
public static void buildStatement() throws SQLException {
statement = connection.createStatement();
}
public static void executeQuery() throws SQLException {
boolean foundResults = statement.execute("SELECT * FROM tblStaff AS x WHERE City='Calgary'");
if(foundResults){
ResultSet set = statement.getResultSet();
if(set!=null) displayResults(set);
}else {
connection.close();
}
}
public static void displayResults(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int columns=metaData.getColumnCount();
String text="";
while(rs.next()){
for(int i=1;i<=columns;++i) {
text+=""+metaData.getColumnName(i)+":\t";
text+=rs.getString(i);
//text+="</"+metaData.getColumnName(i)+">";
text+="\n";
}
text+="\n";
}
System.out.println(text);
}
}
The error mentioned above:
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6957)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(JdbcOdbc.java:3073)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(JdbcOdbcConnection.java:323)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:174)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at tldatabase.DataConnect.makeConnection(DataConnect.java:35)
at tldatabase.Main.main(Main.java:24)
I know the post was years ago but I felt like answering the question for those who are just experiencing this right now. It took me a while to know the answer to the question so here's the solution:
http://wiki.netbeans.org/FaqSettingHeapSize
Follow the "Running the 32-bit JVM".
All you have to do is find the netbeans.conf in the installation folder of your netbeans and change the directory from something like this:
netbeans_jdkhome="C:\Program Files\Java\jdk1.6.0_24"
to this:
netbeans_jdkhome="C:\Program Files (x86)\Java\jdk1.6.0_21"
The problem is netbeans might be running in 64 bit but MS Access only support 32-bit. So doing this would hopefully solve the problem. Also make sure to install this:
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=23734
The main problem lies in the line:
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=TLDATABASEDBM.mdb";
Make sure that the .mdb file is in the correct directory.
Check the file extension as .mdb or .mdbacc.
Also, if you want to use the same DSN every time, it is better to add the DSN(Data Source Name) into the respective system on which the mdb is stored.
I think that your app do not see TLDATABASEDBM.mdb in current directory. You can give full path to this file in connection string or add system DSN in ODBC Manager and then connect to it with connection string like: jdbc:odbc:TLDATABASEDBM
Honestly, I dont like what I am going to say... but, it solved the same issue for me... mysteriously... :(((
on the line where you are defining the database variable, I changed ...(.mdb)... into ...(.mdb, *.accdb)...
All the best for figuring out what difference that made!
package javaapplication1;
import java.sql.*;
public class MSaccess_archive {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// set this to a MS Access DB you have on your machine
String filename = "mdbTEST.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;}"; // add on to the end
// now we can get the connection from the DriverManager
Connection con = DriverManager.getConnection( database ,"","");
Statement stmt = con.createStatement();
stmt.execute("select * from student"); // execute query in table student
ResultSet rs = stmt.getResultSet(); // get any Result that came from our query
if (rs != null)
while ( rs.next() ){
System.out.println("Name: " + rs.getInt("Age") + " ID: "+rs.getString("Course"));
}
stmt.close();
con.close();
}
catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}

Categories