JDBC is not passing the root user to DriverManager.getConnection [closed] - java

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.

Related

How I properly prepare JDBC PreparedStatment? [closed]

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 (?)

App crash when try to connect to DB with JDBC [closed]

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.

java.sql.SLQException: Illegal operation on empty result set [closed]

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 + "'" ;

How to easy upload content to MySql database in Java using JDBC? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I’m beginner and I have problems with using MySql in Java with JDBC.
Can anybody paste a lines of code how to use “SQL UPDATE”.
Or maybe someone know about some good tutorials to learn it?
My code with mistakes:
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
Statement st = conn.createStatement();
String strUpdate = "UPDATE rozchody SET nazwa ='test' ";
ResultSet ra = st.executeQuery(strUpdate);
ResultSet rs = st.executeQuery("select * from rozchody");
while(rs.next()){
System.out.println("wyswietlam: ");
String s = rs.getString("nazwa");
System.out.println(s);
}
} catch (SQLException e) {
System.err.println(e);
} finally {
if (conn != null) {
conn.close();
}
}
For executing UPDATE/INSERT/CREATE statements you should use execute() function of Statement class and not executeQuery().
Corrected code :
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
Statement st = conn.createStatement();
String strUpdate = "UPDATE rozchody SET nazwa ='test' ";
st.execute(strUpdate); // or use executeUpdate()
It will return a boolean value that you can check and proceed.
follow this example here but this is essentially it
String strUpdate = "UPDATE rozchody SET nazwa ='test'";
PreparedStatement preparedStatement = conn.prepareStatement(strUpdate);
// execute insert SQL stetement
preparedStatement.executeUpdate();
When you want to do a UPDATE,INSERT,DELETE on a SQL database, you never receive a resultset.
Use executeUpdate instead of executeQuery.
Only one ResultSet object can be opened for a Statement. You're creating two ResultSet objects with your UPDATE and then your SELECT statements.
Since UPDATE does not return a ResultSet, use st.execute(strUpdate). Then you can retrieve a ResultSet with st.executeQuery("select * from rozchody");
Your fixed code:
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
Statement st = conn.createStatement();
String strUpdate = "UPDATE rozchody SET nazwa ='test' ";
//Change this
st.execute(strUpdate);
ResultSet rs = st.executeQuery("select * from rozchody");
//Now you won't get an error opening a new ResultSet
while(rs.next()){
System.out.println("wyswietlam: ");
String s = rs.getString("nazwa");
System.out.println(s);
}
} catch (SQLException e) {
System.err.println(e);
} finally {
if (conn != null) {
conn.close();
}
}
Note that while the above will work, it is generally better to use PreparedStatements rather than re-using a Statement for different executions. This will help prevent SQL injection, and you should read into it once you have a firmer grasp on how the Statement object works.

How do I connect to access database using java at runtime? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Accessing Access over JDBC (using ODBC?)
I have to do this since we have an unknown amount of access databases the user can select using our program so as to process data from them.
Here is connection code:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=ACCESS_FILE_PATH/FILE_NAME.mdb";
connection = DriverManager.getConnection( database ,"username","password");
I did it as the following:
first , create a db DB1.MDB which contain a table named "table1";
second, config ODBC , create DatabaseSource named "Access2000"。
import java.sql.*;
class database {
public static void main(String args[]) {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:Access2000";
Connection connection=DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String sql="SELECT * FROM table1";
ResultSet rs = statement.executeQuery(sql);
String tt;
while (rs.next()) {
System.out.print("name:" + rs.getString("Name"));
System.out.println("age:" + rs.getString("Age"));
}
rs.close();
connection.close();
}
catch(Exception ex){
System.out.println(ex);
System.exit(0);
}
}
}

Categories

Resources