Reputation: 179
I am trying to execute the following code, which connects my android application to mysql server through JDBC:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Toast;
import net.sourceforge.jtds.jdbc.*;
import net.sourceforge.jtds.jdbcx.*;
import java.sql.*;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "SqlConnection",Toast.LENGTH_SHORT).show();
Connection conn = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://HOSTNAME/DATABASE_NAME;user=USERNAME;password=PASSWORD;");
Toast.makeText(this, "Connection Opened", Toast.LENGTH_SHORT).show();
Statement stmt = conn.createStatement();
ResultSet reset = stmt.executeQuery("select * from Tablename;");
if(reset.next() == true){
//Log.w("Data", reset.getString(1));
Toast.makeText(this, reset.getString(1) , Toast.LENGTH_SHORT).show();
Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
}
conn.close();
}
catch (Exception e){
//Log.w("Error Connection", ""+e.getMessage());
Toast.makeText(this, "Error Connection" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I've added the jtds 1.2.7 in my project, and added the internet permission, The result is Connection ConnectionNull
Upvotes: 0
Views: 8421
Reputation: 26
I believe jTDS is used to work with MS SQL server and not mysql. For connecting to mysql, you would use something like this:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection`enter code here`("jdbc:mysql://hostname:port/dbname","username", "password")
For connecting to MS SQL server using jTDS, you would do something like this, with a port number and instance name :
jdbc:jtds:sqlserver://127.0.0.1:<instance_port>/Payroll
Upvotes: 1