Create a database with username and password in Java - java

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);

Related

Setting up H2 DB programmatically

I'm trying to programmatically update H2 in memory database in my code. For some strange reason I cannot seem to be able to get the create a schema or table. No errors, it just doesn't seem to work. I can create a table using the method below but not a schema
Statement stmt = null;
Class.forName("org.h2.Driver");
try (Connection conn = DriverManager.getConnection("jdbc:h2:tcp://localhost:9090/mem:test", "sa","")) {
//STEP 3: Execute a query
System.out.println("Creating schema in given database...");
stmt = conn.createStatement();
String sql = "CREATE SCHEMA IF NOT EXISTS TEST";
stmt.executeUpdate(sql);
System.out.println("Created schema in given database...");
stmt.close();
The H2 jdbc url, to my knowledge, should be "jdbc:h2:mem:test". Try with this one. See if it helps.

Java Mysql Prepared statement syntax issue

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;
}
}

java.sql.SQLException:Access denied for user

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!

In java JDBC connection error ORA-28000: the account got locked, but db account is not locked

I could connect to Oracle XE, DB from console using the credentials (Username: HR, Password : *****). But I'm getting the error message
ORA-28000: the account got locked
when I try to establish connection from java program using JDBC.
Code:
public static void main(String args[]) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#127.0.0.1:1521:XE";
Connection con = DriverManager.getConnection(url,"USER NAME","PASSWORD");
Statement statement = con.createStatement();
ResultSet resultset = statement.executeQuery("select 'Connected' from dual");
while (resultset.next()) {
System.out.println(resultset.getString(1));
}
statement.close();
con.close();
}
How to connect to DB from this java program?
When connect using the credentials (Username : system, Password : ####) the account got connected without any issue from java program.
However, when connected using the credentials (Username: HR, Password : **) got the error message ORA-28000: the account got locked. But was able to login using these HR credentials from oracle console.
So, to get the connection from java program, did the following:
public static void main(String args[]) throws SQLException, ClassNotFoundException{
String query;
// Connect to system Database first
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#127.0.0.1:1521:XE";
Connection con = DriverManager.getConnection(url,"system","####");
Statement statement = con.createStatement();
query = "alter user HR identified by HR account unlock";
//Unlock the account
ResultSet resultset = statement.executeQuery(query);
//Connect to HR database
con = DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:XE","HR","****");
statement = con.createStatement();
//Fetch all the tables in HR database
query = "select 'Connected' from dual";
resultset = statement.executeQuery(query);
//Prints records fetched
while (resultset.next()) {
System.out.println(resultset.getString(1));
}
statement.close();
con.close();
}
The HR account got unlocked and now able to execute other queries without issues :)
Just change the username to "System" instead of "HR". and that it! you will be able now to connect to your database.

No Database selected when retrieving from mysql website

I have a mysql database that I am trying to retrieve from our website host (godaddy). I followed a format that seems to be right but it tells me that:
java.sql.SQLException: No database selected
Code:
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
// STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM item_master";
ResultSet rs = stmt.executeQuery(sql); //<-- This is where the error is.
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
// Display values
System.out.print("ID: " + id);
}
...
}
I did a print statement of the conn to maybe think the connection could of been null and was shown this:
com.mysql.jdbc.JDBC4Connection#2a6*****
Anyone have any ideas what could cause something like this?
Your URL for your database should include your database name. This is normally your URL followed by a "/DBNAME".
String URL = "jdbc:mysql://localhost:3306/mydb";
Where "mydb" is your database name.
What is the value of DB_URL? As far as I am aware, the URL needs to be of the form:
"WEBURL/DATABASENAME:PORT"
Are you just trying to connect to the WEBURL, without specifying a DATABASE?
I had the same problem.
Just run one more query (before your 'SELECT' statement) to connect to your database.
First:
sql = "USE <yourdatabase>";
ResultSet rs = stmt.executeQuery(sql);
And after:
sql = "SELECT * FROM item_master";
rs = stmt.executeQuery(sql);

Categories

Resources