I have MySQL database "database" in my web. I want to connect it remotly from java. But I get Exception.
I use this code to connect it.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://site.ir:3306/database", username", "password");
Statement st = con.createStatement();
String sql = ("SELECT * FROM users ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
int id = rs.getInt("id");
String str1 = rs.getString("imei");
System.out.print(id+"+++"+str1);
}
con.close();
}catch(Exception e){
e.printStackTrace();
}
I think there's no problem in my code and username has All permission to access database! Please say what's problem!
Related
I am working on a GUI app with MySQL access. When user enters some data in JTextField 'VendorID', I want it to be searched in the database, find the proper line with information and show all the columns in other JtextFields seperately. Actually I wanted this data to be showed in JLabel but unsuccessful, so trying now with JtextFields. Appreciate any help from you.
public void findVendor() {
String vatEntered = vendorID.getText();
try
{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
Statement st = conn.createStatement();
String check = "SELECT * FROM vendorcreation WHERE VAT = 'vatEntered' ";
ResultSet resultSet = st.executeQuery(check);
boolean status = true;
if(resultSet.next()==status){
nameSelected.setText(resultSet.getString(1));
adressSelected.setText(resultSet.getString(2));
countrySelected.setText(resultSet.getString(3));
vatSelected.setText(resultSet.getString(4));
ptermsSelected.setText(resultSet.getString(5));
conn.close();
}
else {
JOptionPane.showMessageDialog(null, "NO DATA FOUND! FIRST YOU MUST CREATE IT", "Inane error",JOptionPane.ERROR_MESSAGE);
dispose();
new CreateVendor().setVisible(true);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
From what I'm understanding, you're having trouble executing the statement?
You need to set up the statement as following:
String check = "SELECT * FROM vendorcreation WHERE VAT = " +vatEntered ;
But it is better to use a prepared statement instead.
String check = "SELECT * FROM vendorcreation WHERE VAT = ?";
PreparedStatement st = conn.prepareStatement(check);
st.setString(1, vatEntered);
ResultSet resultSet = st.executeQuery();
As for categorizing data, the order seems to depend on the order that the column is in the database. What you can also do is to manually set the result by changing the statement:
String check = "SELECT (column1, column2) FROM vendorcreation WHERE VAT = ?"//etc
where resultSet.getString(1); would be data from column1.
I am getting a syntax error with the SQL code within a prepared statement. I have read the other answers on the site and I cannot work out the issue. My code is as follows
private boolean validate_login(String username,String password) {
try{
Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection
String url = "jdbc:mysql://localhost/db_webstore";
String user = "root";
String pw = "Password";
String SQL = "select * from tbl-users where Tbl-UsersUserName=? and Tbl-UsersPassword=?";
Connection conn = DriverManager.getConnection(url, user, pw);
PreparedStatement pst;
pst = conn.prepareStatement(SQL);
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}
The error message is as follows
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-users where Tbl-UsersYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-users where Tbl-Users
Can anyone offer some advice? Thanks in Advance
You are probably missing some dots in your query. Table and column name need to be separated by a dot. Furthermore the table name needs to be quoted as - is not allowed in unquoted identifiers (see here):
String SQL = "select * from `Tbl-Users`"
+ " where `Tbl-Users`.UserName=?"
+ " and `Tbl-Users`.Password=?";
UPDATE:
Added link to MySQL docu on valid identifiers
Quoted table name using `
you should include the port number(which is 3306 for MySQL) in your database connection
accordingly your code should be corrected as follows
private boolean validate_login(String username,String password) {
try{
Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection
String url = "jdbc:mysql://localhost:3306/db_webstore";
String user = "root";
String pw = "Password";
String SQL = "select * from tbl-users where Tbl-UsersUserName=? and Tbl-UsersPassword=?";
Connection conn = DriverManager.getConnection(url, user, pw);
PreparedStatement pst;
pst = conn.prepareStatement(SQL);
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}
I am trying to connect my java application to hostinger.in
I tried this code but no output is displayed.Is this code correct
enter code here
Class.forName(\"com.mysql.jdbc.Driver\");
conn = DriverManager.getConnection(\"jdbc:mysql://mysql.hostinger.in/u869878874_stock\" ,\"u869878874_stock\", \"bhavin\");
stmt = conn.prepareStatement(\"SELECT * FROM logintbl\");
ResultSet rs=null;
rs=stmt.executeQuery();
while (rs.next())
{
usr =usr+rs.getString(\"userid\");
}
jLabel1.setText(usr);
I tried this code but no output is displayed
Is this code correct
Stop using escape sequence in your code and start using string directly.
https://docs.oracle.com/javase/tutorial/java/data/characters.html
Ex.
Class.forName("com.mysql.jdbc.Driver")
Changes to your code.
Connection connection = null;
PreparedStatement pStatement = null;
ResultSet resultSet = null;
String SELECT_SQL = "SELECT * FROM logintbl";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://<host>:<port>/<database_name>", "<user id>", "<password>");
pStatement = connection.prepareStatement(SELECT_SQL);
resultSet = pStatement.executeQuery();
for(;resultSet.next();){
System.out.println("User Id " + resultSet.getString("userid"));
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
How to create a database with username and password in Java?
I created a DB using
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/", USER, PASS);
stmt = conn.createStatement();
stmt.executeUpdate("CREATE DATABASE "+DB_NAME;);
// DB creatd
}
catch(Exception e) {
e.printStackTrace();
}
but now if I connect to this database using:
Connection conn1 = DriverManager.getConnection("jdbc:mysql://localhost/"+DBNAME,user,pass);
what should I enter in the use and pass?
And more importantly how do I create a DB with properties?
One has to have very good reason to create a database via code but You would enter the same login credential as the one that created the database:
DriverManager.getConnection("jdbc:mysql://localhost/"+DBNAME, USER, PASS);
Alternatively once connected to the server you can connect to the database by running following query:
USE DB_NAME
Connection conn1=DriverManager.getConnection("jdbc:mysql://localhost/",user,pass);
stmt = conn1.createStatement();
String sql = "CREATE DATABASE UTSAV";
stmt.executeUpdate(sql);
Hey I am trying to verify the password matches the one they entered with the email I have been searching for the web for a few hours and everything else I have tried does not work this is what i have so far:
try {
Class.forName(driver).newInstance();
Connection conn = (Connection) DriverManager.getConnection
(url + dbName, userName, password);
PreparedStatement checkUserInfo = (PreparedStatement) conn.prepareStatement
("SELECT password FROM profiles WHERE email = ?");
checkUserInfo.setString(1, emailT); //emailT is email pulled from an editText
//checkUserInfo.setString(2, pass1);
//Statement state = (Statement) conn.createStatement();
//String querychk = "SELECT * FROM profiles WHERE email = '"+emailT+"'";
//ResultSet rs = state.executeQuery(querychk);
ResultSet rs = checkUserInfo.executeQuery();
while (rs.next()){
String pass = rs.getString(2);
if (pass.equals(pass1)) {
return success;
}
}
conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
Simply modify your SQL Query to:
"select * from profiles where email=? and password=?"
And be-aware to validate input fields for preventing from SQL injection
And for getting PreparedStatement object or Connection object, you don't have to externally typecast it, cause it is returning the same object as you assigning to it. Even java doc also provided the below statement for the PreparedStatement
PreparedStatement pstmt = con.prepareStatement(Query);