android with JDBC. createStatement() does not exist? - java

I am trying to create a connection with a database using JDBC on my android project. I am following a tutorial which says to import a jar and then create a connection in the activity. Everything is ok, but in the connection statement i get an error
Cannot resolve method 'createStatement()'
if I try to get into the reference of the method, it says
cannot find decleration to go to
This method comes from the jar i have imported? (jtds-1.3.1)
Is there anything else i am missing here?
#Override
protected String doInBackground(String... params)
{
Connection con;
String usernam = params[0];
String passwordd = params[1];
if(usernam.trim().equals("")|| passwordd.trim().equals(""))
z = "Please enter Username and Password";
else
{
try
{
con = connectionclass(un, pass, db, ip); // Connect to database
if (con == null)
{
z = "Check Your Internet Access!";
}
else
{
// Change below query according to your own database.
String query = "select * from owner where mail = '" + usernam.toString() + "' and password = '"+ passwordd.toString() +"' ";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
z = "Login successful";
isSuccess=true;
con.close();
}
else
{
z = "Invalid Credentials!";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
z = ex.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 = (Connection) DriverManager.getConnection(ConnectionURL);
}
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 connection;
}
I got the same problem with the close() method

All you've got to do is specify the class name fully:
java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/product","root","");
No need for a cast, and the error you're reporting will now go away, as the compiler will be looking for the method in the right class.
Or just rename your own class Connection.

Related

JDBC SQLServerConnection "Login failed for user 'sa'"

I am trying connection with database but this error frustrates me . Can anyone help me out what is the problem here?
I want to connect to SQL Server from Eclipse.
public class JDBC_Test {
public static void SQLServerConnection() {
try {
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=Northwind";
String user = "sa";
String password = "832Waseem#";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(url, user, password);
System.out.println("Connection Created Successfully.......");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from categories");
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
}
con.close();
System.out.println("Connection Closed Successfully.......");
} catch (Exception e) {
// System.out.println("Unable to create Connection reason is as below.......");
e.printStackTrace();
}
}
public static void main(String args[]) {
SQLServerConnection();
}
}
My Error:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'sa'. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)

Can't connect to SQL Database (Java, Android Studio)

I have imported the JDBC library, set it to be compiled, and gave the App permission to access Internet.
When a button on Screen is pressed, it should connect to the database and give me the values to implement in the list.
When I press the button, I can see it giving me the "Connecting to database" text, but after about half a second it says "Exception" as defined in that last catch block.
I commented out the three lines of code in onPostExecute, because when I kept them the App would just crash.
public void retrieveData(View view) {
GetData retrieveData = new GetData();
retrieveData.execute();
}
private class GetData extends AsyncTask<String,String,String> {
String msg = "";
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://" + DbStrings.DATABASE_URL + "/" + DbStrings.DATABASE_NAME;
#Override
protected void onPreExecute() {
progress.setText("Connecting to database");
}
#Override
protected String doInBackground(String... strings) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, DbStrings.USERNAME, DbStrings.PASSWORD);
stmt = conn.createStatement();
String sql = "SELECT * FROM video"; //
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
String name = rs.getString("title");
buildNames += name + " ### ";
}
msg = "Process complete.";
rs.close();
conn.close();
stmt.close();
} catch(SQLException connError) {
msg = "An exception was thrown for JDBC.";
connError.printStackTrace();
} catch (ClassNotFoundException e) {
msg = "A Class not found exception was thrown.";
e.printStackTrace();
} catch (java.sql.SQLException e) {
msg = "Exception";
e.printStackTrace();
} finally {
try{
if(stmt != null) {
stmt.close();
}
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
try{
if(conn != null) {
conn.close();
}
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String msg) {
progress.setText(this.msg);
//names = buildNames.substring(0,buildNames.length()-5).split(" ### ");
//itemAdapter = new ItemAdapter(thisContext, buildNames.substring(0,buildNames.length()-5).split(" ### ")); //crashes
//namesList.setAdapter(itemAdapter);
}
}
}
After checking the stack trace I found this:
java.sql.SQLException: Unknown initial character set index '192' received from server.
And so I knew what to search for;
I was using an outdated version of JDBC, (3.x). After importing Version 5.1.46, it is now working :).

net.sourceforge.jtds.jdbc.jtdsresultset#1245 gives output for select itemname from oitm where itemcode='dcs1515' on android

I had developed an android app to connect with MS-sql database it is connected but it does not get correct result it gives
net.sourceforge.jtds.jdbc.jtdsresultset#1245
as result for select itemname from oitm where itemcode='dcs1515'
Please help me to solve this issue. I am using android studio-3.1.0 and ms-sql 2008. I connected android with db using jtds-1.3.1.jar for jdbc connection
class Disp extends AsyncTask<String, String, String> {
#Override
protected void onPostExecute(String s) {
Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... strings) {
connect con = new connect();
String k=null;
ct = con.connectionclass();
if (ct == null){
k="Check Internet";
}
else{
try {
String st = "select itemname from oitm where itemcode='dcs1515'";
Statement smt = ct.createStatement();
ResultSet resultSet = smt.executeQuery(st);
if(resultSet.next())
{
k = resultSet.toString();//"success ";//+resultSet+" deleted";
}
} catch (SQLException e) {
k=e.getMessage();
}
}
return k;
}
}
}
connection class is
public class connect {
String ip = "192.167.0.7";
String db = "RCCLive";
String un = "artika";
String pass = "Acm#157";
public Connection connectionclass()
{
{
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://" + ip + ";" + db + ";user=" + un+ ";password=" + pass + ";";
connection = DriverManager.getConnection(ConnectionURL);
}
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 connection;
}
}
}
k = resultSet.toString();
This should be
k = resultSet.getString(1);
You cannot just take the String value of the ResultSet, you must retrieve the first column of the ResultSet, which is what getString(1) does.

how to prevent a Runnable class from crashing the application?

I'm trying to implement a (more) robust application using Threads.
My JdbcAccess.java more relevant part is:
protected ResultSet readfromSQLServer(String url, String instance, String port, String database, String user, String passwd, String query) throws Exception {
try {
// This will load the SQLServer driver
Class.forName("net.sourceforge.jtds.jdbc.Driver");
// Setup the connection with the DB
String connectionUrl = "";
if (instance != null || instance == "") {
connectionUrl = "jdbc:jtds:sqlserver://" + url + ":" + port + "/" + database + ";instance=" + instance + ";user=" + user + ";password=" + passwd;
} else {
connectionUrl = "jdbc:jtds:sqlserver://" + url + ":" + port + "/" + database + ";user=" + user + ";password=" + passwd;
}
start();
connection = DriverManager.getConnection(connectionUrl);
// Statements allow to issue SQL queries to the database
statement = (Statement) connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
resultSet = statement.executeQuery(query);
} catch (Exception e) {
e.printStackTrace();
}
return resultSet;
}
public void run() {
System.out.println("Running JdbcAccess thread");
try {
// Let the thread sleep for a while.
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void start () {
System.out.println("Starting JdbcAccess thread");
if (thread == null) {
thread = new Thread (this);
thread.start ();
}
}
Problem is that if it has a flawed SQL query the whole application crashes instead of the intended result of just the thread failing / dying out.
What am I doing wrong here?

Error using JDBC "java.lang.NullPointerException" [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I get error on
java.lang.NullPointerException: Attempt to invoke interface method
'java.sql.Statement java.sql.Connection.createStatement()' on a null
object reference at
com.example.jacquesarroyo.onlinelibrary.suggestions$3.onClick(suggestions.java:81)
Here's the code I used:
add = (Button) findViewById(R.id.btnadd);
errorlbl = (TextView) findViewById(R.id.lblerror);
title = (EditText) findViewById(R.id.txttitle);
author = (EditText) findViewById(R.id.txtauthor);
year = (EditText) findViewById(R.id.txtyear);
location = (EditText) findViewById(R.id.txtlocation);
ipaddress = "10.0.0.5";
db = "SampleDatabase";
username = "admin"
password = "admin";
connect = ConnectionHelper(username, password, db, ipaddress);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
st = connect.createStatement();
preparedStatement = connect
.prepareStatement("Insert into Books(Title,Author,Year) values ('"
+ title.getText().toString()
+ "','"
+ author.getText().toString()
+ "','"
+ year.getText().toString() + "')");
preparedStatement.executeUpdate();
errorlbl.setText("Data Added successfully");
} catch (SQLException e) {
errorlbl.setText(e.getMessage().toString());
}
}
});
#SuppressLint("NewApi")
private Connection ConnectionHelper(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 + ";"
+ "databaseName=" + database + ";user=" + user
+ ";password=" + password + ";" + "ssl=false";
connection = DriverManager.getConnection(ConnectionURL);
} catch (SQLException se) {
Log.e("ERROR", se.getMessage());
} catch (ClassNotFoundException e) {
Log.e("ERROR", e.getMessage());
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
return connection;
}
line 81 is: st = connect.createStatement();
NullPointerException means that the variable you are trying to use is not initialized or is null.
Before calling:
connect.createStatement();
you have to initialize the connect object first by:
Connection connect = ConnectionHelper(user,password,database,server);
Keep in mind scope of the variables.

Categories