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?
Related
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)
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.
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 5 years ago.
I wish to get a connection between MySQL and my Java application.
When I run the program I get this error: my logging information is true. This is a project where I should be able to add, insert, delete and update customer information inside my local database.
java.lang.ClassNotFoundException: com/mysql/jdbc/Driver.class
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at sample.Database.Connection.getConnection(Connection.java:26)
at sample.Presentation.Controller.<init>(Controller.java:19)
at sample.Presentation.Main.start(Main.java:13)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
Code
public class Controller {
public Controller(Stage primaryStage) {
ButtonPane buttonPane = new ButtonPane();
AddPane addPane = new AddPane();
VBox vBoxStart = new VBox();
Connection connection = new Connection();
try {
connection = connection.getConnection();
}catch (Exception e){
System.out.println("No connection");
}
Querys querys = new Querys();
HBox hBoxOption = new HBox(buttonPane.ButtonPane(),addPane.getPane());// Menu and add/update/delete
HBox hBoxView = new HBox(); // Calender/tableView
vBoxStart.getChildren().addAll(hBoxOption,hBoxView);
Scene scene = new Scene(vBoxStart,1000,1000);
primaryStage.setScene(scene);
primaryStage.show();
Connection finalConnection = connection;
addPane.getButtonAddCustomer().setOnAction(event ->{
querys.viewTable(finalConnection,"customer");
} );
}
}
public class Connection {
String userName = "root";
String password = "rasmus12";
String dbms = "mysql";
String serverName = "localhost";
String portNumber = "3306";
public Connection getConnection() {
Connection conn = null;
try {
Class.forName("com/mysql/jdbc/Driver.class");
conn = (Connection) DriverManager.getConnection(
"jdbc:" + this.dbms + "://" +
this.serverName +
":" + this.portNumber + "/",
this.userName,this.password);
System.out.println("Connected to database");
} catch (SQLException e) {
System.out.println("SQL Exception in connection");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}
}
public class Querys {
public void viewTable(Connection con, String dbName) {
Statement stmt = null;
String query = "select * " +
"from " + dbName;
try {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
int id = rs.getInt("person_id");
String firstName = rs.getString("person_first_name");
String lastName = rs.getString("person_last_name");
String adresse = rs.getString("person_adresse");
String zip = rs.getString("person_zip");
String city = rs.getString("person_city");
int mobilePhone = rs.getInt("person_mobile_phone");
int phone = rs.getInt("person_phone");
int driverLicenceNumber = rs.getInt("person_driver_licence_number");
String driverSinceDate = rs.getString("person_driver_since_date");
String registrationNumber = rs.getString("person_registration_number");
int orderId = rs.getInt("order_id");
System.out.println(id + "\t" + firstName +
"\t" + lastName + "\t" + adresse +
"\t" + zip +
"\t" + city +
"\t" + mobilePhone +
"\t" + phone +
"\t" + driverLicenceNumber +
"\t" + driverSinceDate +
"\t" + registrationNumber+
"\t" + orderId);
}
} catch (SQLException e) {
System.out.println("SQL Exception");
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
The driver is not correct you have to use :
Class.forName("com.mysql.jdbc.Driver");
Instead of this :
Class.forName("com/mysql/jdbc/Driver.class");
But the call to Class.forName() is no longer necessary since Java 6, you can read this, and like #duffymo mention in his answer, make sure that the driver jar exist in your classpath
ClassNotFoundException means the class loader cannot find the MySQL JDBC driver class.
You need to download the MySQL Connector JAR and add it to your CLASSPATH.
I'd recommend a MySQL JDBC tutorial.
Here's a Java tip: Don't write messages in catch blocks:
catch (SQLException e) {
System.out.println("SQL Exception");
}
Print or log the entire stack trace. It's more information that your message provides.
catch (SQLException e) {
e.printStackTrace();
}
My goal is to get chrome history, this works fine. But my problem is getting "The database file is locked" only when chrome browser is running.
How can I fix this problem?
Can I stop database chrome browser?
this my code:
public class GetChromeHistory
{
public static void main (String[] args)
{
Connection connection= null;
ResultSet resultSet = null;
Statement statement = null;
try
{
// We think, but are not sure, that the line below registers the sqlite drive with JDBC.
Class.forName("org.sqlite.JDBC");
connection = DriverManager
.getConnection("jdbc:sqlite:db.db");
statement = connection.createStatement();
//problem occurs on line below, database file is locked
resultSet = statement
.executeQuery("SELECT * FROM urls where visit_count > 0");
while(resultSet.next())
{
//eventually save into a set or list
System.out.println ("URL [" + resultSet.getString("url") + "]" +
", visit count [" + resultSet.getString("visit_count") + "]");
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
resultSet.close();
statement.close();
connection.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}