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 :).
Related
I have to connect a database to my codes to check a pin code. I have managed to make it but I'm having some problem to make the else part of the if statement to work. I think its the query part which is causing the problem as when I change the if..else statement it works perfectly.
If there is any other way to write this query to get the same result please let me know
thank you
public void getOperation() {
{
Connection conn = null;
String query = "SELECT pin FROM customerdetails WHERE pin='"+Pin+"'";
Statement stmt = null;
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/customerdb", "user","#1234#");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String password = rs.getString("pin");
if (Pin.equals(password)) {
PinCheck = "Pin OK";
} else
{
PinCheck = "Invalid Pin";
}
}
} catch (SQLException e) {
System.err.println(e);
} finally {
if (stmt != null) {
}
if (conn != null ) {
//conn.close();
}
}
}
Having this
String query = "SELECT pin FROM customerdetails WHERE pin='"+Pin+"'";
while (rs.next()) {
String password = rs.getString("pin");
if (Pin.equals(password)) {
PinCheck = "Pin OK";
} else
{
PinCheck = "Invalid Pin";
}
}
makes little sense, as you will always have equal Pin - because you are querying for it. Check for results count. 1== Pin matches, 0== pin invalid.
I'm trying to connect to my DB using JDBC. I wanted to make a method for connection and another method for selecting data. I am getting a red line in Eclipse on the 'Connection con = connectDB();' part. ( See also attached) Cany anyone give me advice?
public class DBJdbc {
//Statement stmt = null;
// connecting to DB
public void connectDB() {
//Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "***", "***");
}
catch(SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
// a method for selecting DB
public static void select() {
//connectDB();
String sql = "SELECT * from SAC_SUR";
try(Connection con = connectDB(); // I'm getting a red line here)
PreparedStatement pstmt = con.prepareStatement(sql)){
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
System.out.println("Id = " + id + "name = " + name);
} //while
} catch(SQLException e) {
System.out.println(e.getMessage());
}
}
red line here!!!
connectDB() method is of void type and not returning anything but when you are calling the method, you are assigning it to variable con. So you need to change the return type of connectDb to the Connection type.
public Connection connectDB() {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "***", "***");
}
catch(SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
You are trying to call non-static method into the static area, which is not allowed in Java. So I made this method static and returning the database connection.
Please update the below method into your code. It will resolve your problem.
public static Connection connectDB() {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://****/SAC?useSSL=false&serverTimezone=UTC", "", "");
} catch(SQLException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
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.
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.
When i run my website it on glassfish server everything works fine but after some time its stop responding and I need to restart glassfish.. I think its cause I not closing the connection. Can someone tell me if this is the problem? if yes how to close it? Here is one of my function.
public Album get_album (String title)
{
try{
//creates a connection to the server
Connection cn = getCon().getConnection();
//prepare my sql string
String sql = "SELECT * FROM albums WHERE Title = ?";
//create prepared statement
PreparedStatement pst = cn.prepareStatement(sql);
//set sql parameters
pst.setString(1, title);
//call the statement and retrieve results
ResultSet rs = pst.executeQuery();
if(rs.next()) {
Album a = new Album();
a.setIdAlbum(rs.getInt("idAlbum"));
a.setTitle(rs.getString("Title"));
a.setYear(rs.getInt("Year"));
a.setIdArtist(rs.getInt("idArtist"));
a.setIdUser(rs.getInt("idUser"));
a.setLike(rs.getInt("Like"));
a.setDislike(rs.getInt("Dislike"));
a.setNeutral(rs.getInt("Neutral"));
a.setViews(rs.getInt("Views"));
return a;
}
}
catch (Exception e) {
String msg = e.getMessage();
}
return null;
}
Assumming the unique error in your application is for not closing the resources after using them, your code should change to:
public Album get_album (String title) {
Connection cn = null;
PreparedStatement pst = null;
ResultSet rs = null;
Album a = null;
try{
//creates a connection to the server
cn = getCon().getConnection();
//prepare my sql string
String sql = "SELECT * FROM albums WHERE Title = ?";
//create prepared statement
pst = cn.prepareStatement(sql);
//set sql parameters
pst.setString(1, title);
//call the statement and retrieve results
rs = pst.executeQuery();
if (rs.next()) {
a = new Album();
a.setIdAlbum(rs.getInt("idAlbum"));
a.setTitle(rs.getString("Title"));
a.setYear(rs.getInt("Year"));
a.setIdArtist(rs.getInt("idArtist"));
a.setIdUser(rs.getInt("idUser"));
a.setLike(rs.getInt("Like"));
a.setDislike(rs.getInt("Dislike"));
a.setNeutral(rs.getInt("Neutral"));
a.setViews(rs.getInt("Views"));
//don't return inside try/catch
//return a;
}
} catch (Exception e) {
String msg = e.getMessage();
//handle your exceptions
//e.g. show them in a logger at least
e.printStacktrace(); //this is not the best way
//this will do it if you have configured a logger for your app
//logger.error("Error when retrieving album.", e);
} finally {
closeResultSet(rs);
closeStatement(pst);
closeConnection(cn);
}
return a;
}
public void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
//handle the exception...
}
}
}
public void closeStatement(Statement st) {
if (st!= null) {
try {
st.close();
} catch (SQLException e) {
//handle the exception...
}
}
}
public void closeResultSet(ResultSet rs) {
if (rs!= null) {
try {
rs.close();
} catch (SQLException e) {
//handle the exception...
}
}
}