Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to get some values from my database, but when I click button (void ButtonClick) my app crashes.
That's my code:
public void ButtonClick() throws Exception {
getConnection();
}
public Connection getConnection() throws Exception {
try {
String username = "*******";
String password = "*******";
String url = "jdbc:mysql://http://**.***.***.***:3306/UserDB";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = (Connection) DriverManager.getConnection(url,username,password);
Statement statement = (Statement) conn.createStatement();
String query = "SELECT * FROM TABLE 'UserDB'";
ResultSet result = statement.executeQuery(query);
while (result.next()) {
String name = result.getString("Username");
int id = result.getInt("ID");
int points = result.getInt("Points");
Toast.makeText(this, name + " " + id + " " + points, Toast.LENGTH_SHORT).show();
}
return conn;
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
return null;
}
(I don't know what's the error because my AVD don't work)
Thanks for help!
Starting with Java 7, there is no need to use forName() method. You are creating a new instance in this way and in the same time you are trying to create a connection using DriverManager.getConnection().
So in order to solve this, just remove the instantiation of the driver using forName() method.
Seeing the screen-shot, please note that you can't access a MySQL database from Android natively. Actually you may be able to use JDBC, but it is not recommended. Please see this post
Hope it helps.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 12 months ago.
Improve this question
Hi, I wanted to add a Password change function to my programm. For that i need to update the password column of the specific user. I researched about it and fount this and tried it:
UPDATE uprtable SET password = '"+password+"' WHERE username = '"+username+"';
I also found out that i need to select the row after it. So I did this too.
SELECT username, password FROM uprtable WHERE username '"+username+"';
The Problem is it doesnt update it and I dont get any Errors where I could get any Info about what is wrong.
Here is the Code direct from the Class:
public void changepw() throws Exception{
Connection con = getConnection();
String passwordID1 = String.valueOf((passwordfield.getPassword()));
String passwordID2 = String.valueOf((passwordfield2.getPassword()));
String passwordID3 = String.valueOf((passwordfield3.getPassword()));
if (passwordID1.equals(resultSet.getString("password"))) {
if (passwordID2.equals(passwordID3)) {
String userID = resultSet.getString("username");
try {
PreparedStatement statementpwchange = con.prepareStatement("UPDATE uprtable SET password = '"+passwordID2+"' WHERE username = '"+userID+"'");
PreparedStatement statementpwchangeconfirm = con.prepareStatement("SELECT username, password, rank FROM uprtable WHERE username = '"+userID+"'");
System.out.println("Updated");
frame.dispose();
}
catch(Exception e){
System.out.println(e);
}
}
else {
messageLabel.setForeground(Color.RED);
messageLabel.setText("The Passwords do not match");
}
}
}
If you need more Information about the Code, feel free to ask.
Thank you in advance!
You have prepared the statement but have not executed the statement. For reference: INSERT (as well as UPDATE and DELETE) statements should use executeUpdate().
SELECT statements should use executeQuery().
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I started to work at my own Minecraft plugin. I need database connection to do so. I try to execute query and I get errors that I can't find solutions for.
Here is the code of function that I'm using:
public void checkIfUserExists(String login, Connection connection) {
String query = "SELECT login FROM edvault.users WHERE login = ?";
try {
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, login);
ResultSet rs = statement.executeQuery();
if (!rs.next()){
String query2 = "INSERT INTO edvault.users (login) VALUES ?";
PreparedStatement statement2 = connection.prepareStatement(query2);
statement2.setString(1 , login);
int result = statement2.executeUpdate();
if (result != 1){
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "<DBINFO> ERROR OCCURRED WHILE INSERTING NEW USER" +
" TO DATABASE");
} else {
Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "<DBINFO> ADDED NEW USER TO DATABASE : LOGIN - "+
login);
}
} else
Bukkit.getConsoleSender().sendMessage("<DBINFO> USER ALREADY EXISTS IN DATABASE");
} catch (SQLException e) {
e.printStackTrace();
}
}
And here is the exception that console returns to me (this is exception for the first query, where login is xEdziu):
[22:26:21] [Server thread/WARN]: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'xEdziu' in 'where clause'
Replace
INSERT INTO edvault.users (login) VALUES ?
with
INSERT INTO edvault.users (login) VALUES (?)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I got a login system in java and i want to get de user, password and type of user from database. But when i run the programe i got the folowing error: java.sql.SLQException: Illegal operation on empty result set
Code:
conn=MysqlConnect.ConnectDB();
String Sql="Select*from utilizador where Nome='" + Username +"' and Password='" + Password +"' and Permissao'" + Permissao + "'" ;
try{
pst=conn.prepareStatement(Sql);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(Sql);
int permissao = rs.getInt("Permissao");
String nome = rs.getString("Nome");
String password = rs.getString("Password");
if(rs.next()){
Your code has various issues:
You missed an = after and Permissao
From your code it seems you are looking for a user filtering by the following fields: Username, Password and Permissao, so you should have 3 variables defined
You are trying to access the ResultSet (using rs.getXXX) before selecting any rows. After the executeQuery method you "fill" a ResultSet but his index is not pointing to any valid "database rows" so you need to call "rs.next()" in order to move the index to the first row. Consecutive calls move the index ahead of 1 position every time until the ResultSet finishes.
Having said so, you should:
Use a prepared statement that prevents sql injection and other typo/character errors as it automatically escapes parameter values.
In the prepared statement use ? to define the parameters you'll need to set using s.set<TypeOfField>
Check if ResultSet has rows before using rs.get
Close connection, statement, and result set in the finally clause, so the resources will be closed either if there is or there is not an exception. Doing so you will prevent memory leak due to opened resources that you are not using anymore.
You should have 3 variable to perform the select: (I suppose)
Username of type String
Password of type String
Permissao of type int/Integer
Try using the following code, adapted to your needs.
Connection c = DB.dbConnect(null);
PreparedStatement s = null;
ResultSet rs = null;
try {
final String SQL = " Select * from utilizador where Nome=? and Password=? and Permissao = ? ";
s = c.prepareStatement(SQL);
int i = 1;
s.setString(i++, Username);
s.setString(i++, Password);
s.setInt(i++, Permissao);
rs = s.executeQuery();
if (rs.next()) {
int permissao = rs.getInt("Permissao");
String nome = rs.getString("Nome");
String password = rs.getString("Password");
}
} catch (SQLException e) {
// exception handler
} finally {
try {
if (rs != null)
rs.close();
} catch (Exception e) {
}
try {
if (s != null)
s.close();
} catch (Exception e) {
}try {
if (c != null)
c.close();
} catch (Exception e) {
}
}
Bad looking, unreadable code.
Here's your problem:
String nome = rs.getString("Nome");
String password = rs.getString("Password");
You try to access values from the ResultSet before checking to see if it has any rows.
Clearly the issue is with your query which is lacking proper quotes and spaces. It should be
String Sql="Select * from utilizador where Nome = '" + Username +"' and Password='" + Password +"' and Permissao = '" + Permissao + "'" ;
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Here is my code :
import java.sql.*;
import com.mysql.jdbc.Statement;
public class Test {
public static void main(String[] args) throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Something happened badly");
e.printStackTrace();
}
final String DB_URL = "jdbc:mysql://localhost/";
final String USER = "root";
final String PASSWORD = "XXXXX";
Connection conn = DriverManager.getConnection(DB_URL,USER,PASSWORD);
//String db = "CREATE DATABASE TEST1";
String use_db = "USE football_manager";
Statement stmt;
String createTable = "CREATE TABLE coffees "
+ "(COF_NAME VARCHAR(30),"
+ "SUPPLIER VARCHAR(30),"
+ "PRICE FLOAT,"
+ "STOCK INTEGER)";
try {
conn = DriverManager.getConnection(DB_URL);
//stmt = (Statement) conn.createStatement();
// stmt.executeUpdate(db);
stmt = (Statement) conn.createStatement();
stmt.executeUpdate(use_db);
stmt = (Statement) conn.createStatement();
stmt.executeUpdate(createTable);
stmt.close();
conn.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
}
And here is the message I keep getting in my console:
SQLException: Access denied for user ''#'localhost' to database
As you can see the user name has been left blank. I'm using Eclipse Luna. This worked fine when I used Eclipse Kepler.
Your problem is here:
conn = DriverManager.getConnection(DB_URL);
You're obtaining a second connection object but not sending the user credentials. I'm not sure why you want/need to open a second connection, use the first one.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
so I'm trying to connect to a database using java.. there's a problem at a function I wrote getOutSymptoms.
Here's the code
package database_console;
import java.sql.*;
public class DBConnect {
private Connection con;
private Statement st;
private ResultSet rs;
public DBConnect(){
try {
Class.forName("com.mysql.jdbc.Driver");
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users", "root", "admin");
st = con.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getOutSymptoms(int userID) throws SQLException{
String query = "SELECT `user`.`out_symptoms` FROM user WHERE (`user`.`id` =" + userID + ")";
rs = st.executeQuery(query);
int out_symptoms_value = rs.getInt("out_symptoms");
st.close();
return out_symptoms_value;
}
the error is at the getOutSymptoms function, at the line:
int out_symptoms_value = rs.getInt("out_symptoms");
why is that? and how can I fix it?
thank u so much.
You need to iterate through your result set in order to get the returned rows. When you first get your new ResultSet, it's not pointing to any particular row (its pointer is set to a row before first) and you need to call rs.next() method at least once to get to the actual results.
If you know there can be only one result you can do something like this:
if (rs.next()) {
int out_symptoms_value = rs.getInt("out_symptoms");
//do other stuff
} else {
//query returned no results
}
If you expect to have more than one row returned, then you can do this:
while(rs.next()) {
int out_symptoms_value = rs.getInt("out_symptoms");
//do the rest of processing
}
TLDR: You need to call rs.next() at least once to get to the actual results.
In order to start using a ResultSet, you must call the next() method. Although you haven't stated the exact error, you will definitely run into this problem unless it is added before you call getInt().
http://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html
you need to iterate through the resultSet object using rs.next() to get the value. resultSet doesn't point to the actual row but when you call rs.next() it points to first result.
while(rs.next(){
int d = rs.getInt(" ");
}
rs.next() returns a boolean value , incase nothing is returned the loop will not execute & you will not get an Exception at runtime.
You have already passed the database name in connection string so change this
String query = "SELECT `user`.`out_symptoms` FROM user WHERE (`user`.`id` =" + userID + ")";
to
String query = "SELECT out_symptoms FROM tableName WHERE id =" + userID;
Then just iterate over the obtained ResultSet like this
while(rs.next()) {
int out_symptoms_value = rs.getInt("out_symptoms");
}
Moreover its good to use PreparedStatement instead of Statement which cna prevent you from sql injection