I have a database with User information, and I wanted to make a public static to return the database integers at any given time without having to make a void for every single one, but it's giving me this error:
0
java.sql.SQLException: not implemented by SQLite JDBC driver
at org.sqlite.jdbc3.JDBC3PreparedStatement.unused(JDBC3PreparedStatement.java:466)
at org.sqlite.jdbc3.JDBC3PreparedStatement.executeQuery(JDBC3PreparedStatement.java:506)
at dysanix.main.checkUserColumnInt(main.java:726)
at dysanix.main.main(main.java:50)
And this is my code:
public static int checkUserColumnInt(String column, String user) {
try {
Connection connection = DriverManager.getConnection("jdbc:sqlite:Database.db");
String query = "Select ? from userSettings WHERE user = ?";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, column);
statement.setString(2, user);
ResultSet result = statement.executeQuery(query);
result.next();
int columnResult = result.getInt(column);
return columnResult;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
Does someone understand what I'm doing wrong? I tried to Google things, but changing code around moved me from one error to the next... so I'm not really certain anymore at this point.
I am running JDBC driver sqlite-jdbc-3.8.11.2.jar
PreparedStatement.executeQuery(String sql) is not implemented. I guess you just want to call executeQuery(). The query is defined by the PreparedStatement already.
Related
It Takes Too Long For Me To Create And Send PreparedStatement's or ResultSet.
How Can I Get MaxID From SQL in Java Method?
Writed this but not working...
private static int getLastId()
{
int returned=0;
try
{
PreparedStatement stat;
ResultSet rs;
String sql="select max(id) from home";
stat=conn.prepareStatement(sql);
rs=stat.executeQuery();
while(rs.next())
{
returned = rs.getInt("id")+1;// just want a new id for new person
}
}
catch (Exception e)
{
System.out.println(""+e);
}
return returned;
}
I Tried To Use It Like This...
//reseting every thing and get lastId+1;
System.out.println("added");
field_name.setText("");
field_pass.setText("");
int temp= getLastId();
field_id.setText(""+temp);
But It Returns 0!
I Don't Have any SQL error.
Did I Use It Wrong?
or ?
Thanks For Help.
You have a few problems here, one of which is that in your current code you aren't actually accessing the max(id) which you put in the query. One way around this is to assign an alias:
PreparedStatement stat;
ResultSet rs;
String sql = "SELECT MAX(id) AS max_id FROM home";
stat = conn.prepareStatement(sql);
rs = stat.executeQuery();
if (rs.next()) {
returned = rs.getInt("max_id") + 1;
}
This fixes the syntax problem, but there is still the problem of whether this is the best way to get the next id. I would recommend that you switch to using an auto increment column, which MySQL will manage for you. Then, you don't need to worry about keeping track of the latest ID value. In fact, you don't even need to specify a value when inserting; the database will handle this for you.
This piece of code uses an SQL query to return how many entries there are in a certain table.
public int countAmountOfEntries() {
int amount;
try (Connection conn = DriverManager.getConnection(Connection.JDBC_URL);
PreparedStatement query = conn.prepareStatement("SELECT COUNT(*) FROM Table")) {
try (ResultSet rs = query.executeQuery();) {
if (rs.next()) {
amount = rs.getInt("COUNT(*)");
}
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
return amount;
}
This should return any int other than 0. Initialising the variable to 0 will result in a NullPointerException being thrown as I'm using the return value of this to set the length of an array. Using the same code in another class returns the int it should return. I've tried using an alias for the COUNT(*) but to no avail.
Running the query directly into MySQL returns the int as well. I've tried removing the nested try (it was pretty much obsolete since I know it won't throw an exception if no one messes with my DB).
Did you register the JDBC driver before using it?
Class.forName("com.mysql.jdbc.Driver");
Is it required to provide an username/password upon connecting?
DriverManager.getConnection(url, user, pass);
Did you create a Connection class yourself which overwrites the Connection class returned upon opening the connection. The reason I ask this is because you retrieve the URL to connect to using Connection.JDBC_URL which is (as far as I know) not in the Connection class.
Is there already a connection opened and your database only allows 1 open connection?
Note: do not forget to close the resultset, statement, and connection before returning:
rs.close();
query.close();
conn.close();
Besides that, restructure your function because a try without catch does not help at all.
This looks really weird:
amount = rs.getInt("COUNT(*)");
Try this instead
amount = rs.getInt(1);
I have users table in MySQL and I created a stored procedure so that when get username and password from swing textfields passed them into stored procedure and learn if is there exist that user to login, but I can not get resultset actually in phpMyAdmin stored procedure work properly but in netbeans can not get resultset and runtime never stop in console , running always.
I do not think there is a problem in my code somewhere else because it is so simple code.
Here is my stored procedure in MySQL
SELECT * FROM `users` WHERE `users`.`E-Mail` = #p0 AND `users`.`Password` = #p1
it takes two parameter varchar and I tried before those as a text
Here is the specific part of my java code
public void loginPass(String email, String password){
try {
DriverManager.registerDriver((Driver) Class.forName("com.mysql.jdbc.Driver").newInstance());
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/askdocdb","root","");
CallableStatement mystatement = connection.prepareCall("{CALL sp_Login (?, ?)}");
mystatement.setString(1, email);
mystatement.setString(2, password);
// mystatement.setString("#p0", email);
// mystatement.setString("#p1", password);
boolean situation = mystatement.execute();
System.out.println(situation);
// resultset = mystatement.executeQuery();
resultset = mystatement.getResultSet();
String res = resultset.getString(2);
System.out.println(res);
// resultset = mystatement.executeQuery();
while(resultset.next()){
System.out.println("asdsad");
}
resultset.close();
} catch (Exception e) {
}
}
The reason of comment lines, I tried any possible combination of syntax
situation returns true
res does not return
and can not enter into while statement
Thank you for your support and comments already now.
It's difficult to say what exactly is wrong with your code as there are quite a few possible points for failure if you choose to use a stored procedure for this simple task (incorrect syntax in the procedure, problems with getting the return value over JDBC, etc). I would simply run the SQL query over JDBC for checking the credentials:
public void registerDriver() {
try {
DriverManager.registerDriver((Driver) Class.forName(
"com.mysql.jdbc.Driver").newInstance());
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException | SQLException e) {
throw new RuntimeException("Could not register MySQL driver!", e);
}
}
public boolean checkLogin(String email, String password) {
try (Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/askdocdb", "root", "");
PreparedStatement ps = connection
.prepareStatement("SELECT 1 FROM users WHERE "
+ "E-Mail = ? AND Password = ?")) {
ps.setString(1, email);
ps.setString(2, password);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return true; // username and password match
} else {
return false; // no row returned, i.e. no match
}
}
} catch (SQLException e) {
throw new RuntimeException(
"Error while checking user credentials!", e);
}
}
What was changed:
JDBC driver registration has been extracted into a separate method (registerDriver()), which you only need to call once (e.g. after the program has started), not each time you check for credentials.
Resources such as Connection, PreparedStatement and ResultSet are now being closed properly (even if an exception is thrown) because they are declared through the try-with-resources statement.
The method now returns a boolean that corresponds to whether the credentials were valid or not, making it easier to use from calling code.
Exceptions that cannot be handled (e.g. SQLException) are rethrown as RuntimeExceptions (instead of just swallowing them in an empty catch block).
Basically, when an SQLException is thrown, either there is a programming error in the code (invalid query syntax) or something severely wrong with the database. In either case, the only option is usually to halt your program. You can declare throws SQLException in the method signature if you'd want to handle the situation in the calling method instead.
Finally, it needs to be mentioned that you should never store passwords in the database as plain text, to avoid anyone with read access to the db to login as an arbitrary user. Instead, you should store password hashes, or even better, salted hashes. More on this e.g. in Best way to store password in database.
How do I insert a list of values into a column in a MySQL table.
Here is my project:
public void settingAmount(List<String>lst)throws Exception{
// Accessing driver from jar files
Class.forName("com.mysql.jdbc.Driver");
// here we create a variable for the connection called con
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ozon","root","root");
// here we create our query
Statement stmt = (Statement) con.createStatement();
//performing insert operation :)
lst.toArray(ss);
for(String ins:ss){
double d=Double.parseDouble(ins);
String insert = "INSERT INTO storage_other(total) VALUES ("+ins+");";
//String insert = "INSERT INTO storage_other(amount) VALUES ("+ls+");";
// Here we are going to Execute the query
stmt.executeUpdate(insert);
System.out.print("Done Seccesfully :)");
}
}
What you want to do is use batches. Batches allow you to send a list of statements to be done at the same time.
Here is an example
connection.setAutoCommit(false);
PreparedStatement ps = connection.prepareStatement("INSERT INTO storage_other(total) VALUES (?)");
for (String ins:ss){
ps.setObject(1, d);
ps.addBatch();
}
ps.executeBatch();
connection.commit();
This will be significantly faster than individual inserts on any table with indexes.
This is a method I used in order to insert some data in an Oracle SQL database.
private boolean submit(Connection con, String query){
try {
PreparedStatement preStatement;
preStatement = con.prepareStatement(query);
preStatement.executeQuery();
preStatement.close();
return true;
}catch (Exception e) {
System.out.println("Exception cought, updating log.");
return false;
}
}
You can prepare your insert statement and call this function to perform the action. Call it using your connection object and the query. It shall return true on completion false in case something goes wrong. If you want to log any errors, use e.getMessage() to get the error message as a String in the exception block.
As mentioned in the comments, try to use the PreparedStatement object to avoid SQL Injection attacks and also try to trim any ' you might have in your data.
Here's how I'd recommend you do it. A few thoughts:
Give the Connection to the object. That method should do one thing: the INSERT.
Should be transactional.
Should clean up resources when done.
Tell users to provide a List of Doubles if that is what the amounts are. Don't parse; let clients do that.
Here is complete code:
public class Inserter {
private static final String INSERT_SQL = "INSERT INTO storage_other(total) VALUES(?))";
private Connection connection;
public Inserter(Connection connection) {
this.connection = connection;
}
public int settingAmount(List<Double> amounts)throws SQLException {
int numAmountsInserted = 0;
PreparedStatement ps = null;
this.connection.setAutoCommit(false);
try {
ps = this.connection.prepareStatement(INSERT_SQL);
for(Double amount : amounts) {
ps.setDouble(1, amount);
numAmountsInserted += ps.executeUpdate();
}
this.connection.commit();
} catch (SQLException e) {
DatabaseUtils.rollback(this.connection);
throw e;
} finally {
DatabaseUtils.close(ps);
this.connection.setAutoCommit(true);
}
return numAmountsInserted;
}
}
I am trying to create a simple web app that saves user data from a form to a database and reads the content of the database back to browser upon request. Following are the functions I have written so far.
connectToDB() // connects to database
addEmployee() // adds employee to database
displayEmployee() // returns a resultSet
isExisted(int staffID) // checks if the staff already exists
Database connection function:
public void connectToDB(){
try{
// load Apache derby driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
} catch(ClassNotFoundException e) {
System.err.println(e);
}
try{
connection = DriverManager.getConnection(DBNAME, USERNAME, PASSWORD);
} catch(SQLException e){
System.err.println(e);
}
} // end connectToDB
Display Employee function:
public ResultSet displayEmployee(){
connectToDB();
ResultSet result = null;
try{
Statement stmt = connection.createStatement();
String query = "SELECT * FROM APP.ADDRESSBOOK";
result = stmt.executeQuery(query);
} catch(SQLException e) {
System.err.println(e);
}
return result;
}
Check if employee exists:
public boolean isExisted(int StaffID){
connectToDB();
try{
Statement stmt = connection.createStatement();
String query = "SELECT StaffNum FROM APP.ADDRESSBOOK WHERE StaffNum = " + staff_number;
ResultSet result = stmt.executeQuery(query);
while(result.next()){
int temp = result.getInt(1);
if(temp == staff_number){return true;}
}
} catch(SQLException e) {
System.err.println(e);
}
return false;
}
As you can see, if you compare the displayEmployee() and isExisted(), I am repeating mysel. Both the function works but I am looking to refactor the code. In those function I havent closed the connection. If there were 20 functions in the web app that connects to the database my code would stink.
I am looking something like this:
* THIS CODE DOESNT WORK ******
private Statement queryDB(query){
connectToDB();
Statement stmt;
try{
stmt = connection.createStatement();
} catch(SQLException e) {
System.err.println(e);
}
return stmt;
// code for closing connection
}
public ResultSet DisplayEmployee(){
String query = "SELECT * FROM APP.ADDRESSBOOK";
Statement stmt = queryDB(query);
ResultSet result = stmt.executeQuery(query);
return result;
}
Thanks.
Using raw JDBC produces a lot of unsightly boilerplate code. One solution is to use Spring JDBC Template.
In addition you will get the sql exception hierarchy which will manage the underlying JDBC exceptions automatically as runtime exceptions.
For more see:
Introduction to Spring Framework JDBC
A couple of comments:
The catch statement of ClassNotFoundException should throw an exception and shouldn't continue further.
It is not a good idea to return resultsets from a method that obtained them upon statement execution, since it is the responsibility of that method to close it. Instead, you should either read out the results into objects or cache them into CachedRowSet if your downstream functions expect a resultset.
The connectToDB method should return a successful connection or throw exception.
You could write a method that takes in an SQL query and return the results as objects so that this method can be used for retrieving based on different criteria as long you are retrieving the objects of same type.
isExisted is using staff_number which I think you intend it to be staffID. If you found a row with this value, then there is no need to check if the result set contained the row with this value, right?
My two cents!