screenshot of the codeI want to use statement in connecting mysql and java database, but the code is giving me errors, I want to know where did I go wrong and how I should do it without getting errore
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/sms","root","");
Statement st= (Statement)conn.createStatement();
String sql= "select * from user_login";
}
catch(Exception e){
}![this is the screenshot of the code](https://i.stack.imgur.com/lo8Yo.png)
I tried using this
Alright, so to do JDBC with MySql you need 4 things
Driver Class
Connection URL
Username
Password
Assuming you have already created the database, with name database_name and table data that has 3 columns as id, first_name & last_name
Connection and showing the data in as follows:
import java.sql.*;
import java.util.*;
class ConnectionToDatabase{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name","username","Pa$$word");
Statement statement = connnection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from data");
while(resultSet.next()){
System.out.println(resultSet.getInt(1) + " " + resultSet.getString(2) + " " + resultSet.getString(3));
connection.close();
}
}catch(Exception e) { System.out.println(e); }
}
}
And of course, you can use Spring Boot, where a file named application.properties exists inside java.resources, you can specify the connection as - (Copied from Spring docs)
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=databaseusername
spring.datasource.password=databasepassword
Related
I'm a little new at that, but after starting my ec2 instance, and installing MySQL instance through RDS, I manage to connect to it through MySQL Workbench using ssh (.pem file).
My problem is I can't seem to have it right, when I'm trying to connect with jdbc, how exactly the authentication suppose to be done?
Here is my code, hope somebody can give me a hint on how to proceed:
public void create_table(){
Connection c = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection ("jdbc:mysql://127.0.0.1:3306/test","root", "password");
// c = DriverManager.getConnection ("jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test","user="+"root"+"password=root", "");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE USERS " +
"(ID INT PRIMARY KEY ," +
" DEVICE TEXT NOT NULL, " +
" NAME TEXT NOT NULL)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
EDIT
I forgot few important details...
I wrote my code in Java using Jersey and servelt.
I Uploaded my WAR file to my ec2 instance.
Now after both web-app and MySQL server are running on the same instance, I want to build the communication..
Thank you!
Your SQL Syntax is incorrect. Text values are inserted as VARCHAR type in SQL. You can change the length of the text value depending on your need by changing the value with in the bracktes in VARCHAR(HERE). Try this code.
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/STUDENTS";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE USERS " +
"(ID INTEGER not NULL," +
" DEVICE VARCHAR(255) not NULL," +
" NAME VARCHAR(255) not NULL,"+
"PRIMARY KEY (ID))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
how exactly the authentication suppose to be done?
you can use one of the form you use in your example but there are wrong things in both
c = DriverManager.getConnection ("jdbc:mysql://127.0.0.1:3306/test","root", "password");
you connect to localhost, if you have your test db on RDS you need to reference the end point of RDS like your second example
c = DriverManager.getConnection ("jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test","user="+"root"+"password=root", "");
Here the end point will be correct but the string to connect is wrong. You can use the following form
String jdbcUrl = "jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test?user=root&password=password";
Connection con = DriverManager.getConnection(jdbcUrl);
or
String url = "jdbc:mysql://mydatabase.test.us-east-1.rds.amazonaws.com:3306/";
String userName = "root";
String password = "password";
String dbName = "test";
Connection connection = DriverManager.getConnection(url + dbName, userName, password);
To find precisely your database end-point, login to the RDS console (make sure to select the right region if not us-east-1), select your database and the Endpoint will be there
The other potential issue you might run is on Security Groups
The DB instance was created using a security group that does not authorize connections from the device or Amazon EC2 instance where the MySQL application or utility is running. If the DB instance was created in a VPC, it must have a VPC security group that authorizes the connections. If the DB instance was created outside of a VPC, it must have a DB security group that authorizes the connections.
Check your security group rules for both the RDS DB and the ec2 instance and make sure you can connect that the ec2 instance has access to RDS server
Using standard JDBC code for JAVA-ORACLE connection however not working.
This may be asked earlier but i am not able to debug it myself so asking here.
Request for help.
Code:
import java.sql.*;
class OracleCon {
public static void main(String args[]) {
try {
// step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
// step2 create the connection object
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe", "system",
"nikhil.nik");
/*
* Hostname: Host system for the Oracle database. For your Express
* Edition database, the hostname is localhost. Port: Listener port.
* The default is 1521. SID: Database name. The default for Express
* Edition is xe.
*/
// step3 create the statement object
Statement stmt = con.createStatement();
// step4 execute query
ResultSet rs = stmt.executeQuery("SELECT TEST_NAME FROM TEST1");
// System.out.println(rs);
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " "
+ rs.getString(3));
// step5 close the connection object
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Stacktrace:
java.sql.SQLException: Fail to convert to internal representation
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.CharCommonAccessor.getInt(CharCommonAccessor.java:132)
at oracle.jdbc.driver.OracleResultSetImpl.getInt(OracleResultSetImpl.java:521)
at dbPrograms.OracleCon.main(OracleCon.java:31)
You selected column TEST_NAME and extracted its values as int. This operation fails because Oracle cannot convert the values accordingly. Use the ResultSet method suitable for the column type.
Also you select one column and access three columns in the ResultSet so you might want to adjust the select command.
I am trying to connect to a remote hive server. I have the following maven java code :
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException {
try {
// Register driver and create driver instance
Class.forName(driverName);
} catch (ClassNotFoundException ex) {
Logger.getLogger(ForHive.class.getName()).log(Level.SEVERE, null, ex);
}
// get connection
System.out.println("before trying to connect");
Connection con = DriverManager.getConnection("jdbc:hive://<hostip>:10000/", "hive", "");
System.out.println("connected");
// create statement
Statement stmt = con.createStatement();
// execute statement
stmt.executeQuery("CREATE TABLE IF NOT EXISTS "
+" consultant ( eid int, name String, "
+" salary String, destignation String)"
+" COMMENT ‘Employee details’"
+" ROW FORMAT DELIMITED"
+" FIELDS TERMINATED BY ‘\t’"
+" LINES TERMINATED BY ‘\n’"
+" STORED AS TEXTFILE;");
System.out.println("Table employee created.");
con.close();
}
But when I execute it gets stuck while trying to connect to the server and throws no exception either.
Try to use org.apache.hive.jdbc.HiveDriver driver.
Connection string
jdbc:hive2://<host>:10000/
Following ways are reasons for your problem.
1.Hive JDBC Class path is "org.apache.hive.jdbc.HiveDriver" and not "org.apache.hadoop.hive.jdbc.HiveDriver".
2.For hive server,
You can able to use like below.
Connection con = DriverManager.getConnection("jdbc:hive://:10000/default", "", "");
3.If you have using hiveserver2,
you have use below connection.
Connection con = DriverManager.getConnection("jdbc:hive2://:10000/default", "", "");
Above ways are surely helpful to you
I am trying to connect java derby db and insert into a table. Everything goes ok but data is not inserted although there is no error at all. Cn you please let me know whats wrong? i tried to change the code and even created new database n table still same. Code works wihtout error but data is not inserted.
Here is my code
databasetest.java
package databasetest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DatabaseTest {
public static void main(String[] args) {
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
System.out.println(" class found " );
}catch(Exception e){
System.out.println("Not found driver class" + e);
};
try{
Connection conn = null;
String pass =null;
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/user","APP",pass);
System.out.println(" Connected to database " );
try{
Statement st;
System.out.println(" inserted");
conn.close();
}catch(Exception e){
System.out.println(" Eror in inserting" + e );
}
}catch(Exception e){
System.out.println("Mistake happnd " + e);
}
}
}
here is run result
run:
class found
Connected to database
inserted
BUILD SUCCESSFUL (total time: 0 seconds)
Please can some one tell me whats going wrong?
Thanks in advance
The problem seems to reside here: Statement st;. You are creating a statement object but you are not associating any queries to it.
Please take a look at this Oracle Tutorial for more information on the matter.
Your code is not actually trying to insert anything.
Statement st;
System.out.println(" inserted");
conn.close();
This doesn't really do anything other than close the connection.
Usually you will want to create a PreparedStatement with a query like
PreparedStatement st = conn.prepareStatement("place your SQL Query here");
st.execute();
alternatively you could look into the API for PreparedStatement.
If you are set on using a regular Statement or your query is simple and does not involve insecure input, you can use
Statement stmt = conn.createStatement();
stmt.execute("Simple SQL Query here");
from the code looks like You have just created the connection with database.
there is no code to insert something into the database.
add the following code to insert some value into your database.
Statement stmt=con.createStatement();
String query="Insert into table_name values (comma separated sequential column value)"; //here comes your insertion query
ResultSet rs=stmt.executeQuery(query);
I am trying to connect to sql server 2005 from my Java application using
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionurl = "jdbc:sqlserver://servername\\SQLEXPRESS;" + "database=master";
Connection con = DriverManager.getConnection(connectionurl);
System.out.println("Connected to SQL Server");
String sql = "select * from employee";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getString(1) + " " + rs.getString(2));
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
On executing it, I do not get any output / error at the console. What am I missing?
Maybe there is no records in the table employee.
Or it throws an Exception whose e.getMessage() returns ""(I don't think so,but to avoid it,You can use e.printStackTrace() instead).
actually,the correct answer is...
when you insert the record in sql prompt we have to commit that record by command commit;
sql>commit;
even thought when you insert the record after that you can check by command select *from table;
record is inserted successfully...record is there
but in command prompt when we executing java program records are not displaying....
so commit the record when u inserted..
thankyou