package main.java;
import java.sql.*;
public class SQLSetup {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/test_db";
// Database credentials
static final String USER = "Halli";
static final String PASS = "dragon";
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 REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" 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!");
}
}
Why is CREATE TABLE REGISTRATION giving me the error "Unrecognized statement"? I am using Intellij, Java 13 and Maven and MySQL server.
This is just something to get my question through since the template is complaining about me not giving enough details and a lot of code, but I am not sure what more to say about the problem.
It did not even occur to me that I could run the code with Intellij giving me a red error on this, but it did not matter - I tried to run the code and Voila - it created a table, even with this error message.
Related
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
I am trying to retrieve data from SYBASE database and copy retrieved data in a table in MySQL. I am able to connect both databases separately (i.e) using jTDS driver for SYBASE and Jdbc_driver for MySQL.
Now I want to connect both databases simultaneously in a single program. But I confused what should be written in Class.forName().
I have used Class.forName(JDBC_DRIVER); for MySQL and Class.forName("net.sourceforge.jtds.jdbc.Driver"); for SYBASE.
Sybase:
public static void main(String[] args) {
String a;
String b;
String c;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:jtds:sybase://10.159.252.29:4100/fmdb","sa","Changeme_123");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("selecttbl_alm_log_2000000000.Csn,"
+ "tbl_alm_log_2000000000.IsCleared,"
+ "tbl_alm_log_2000000000.Id"
+ "From fmdb.dbo.tbl_alm_log_2000000000"
+ "Where IsCleared = 0");
while(rs.next()) {
a = rs.getString(1);
b = rs.getString(2);
c = rs.getString(3);
System.out.println(a+" "+b+" "+c);
}
con.close();
} catch(Exception e) {
System.out.println(e);
}
}
MySQL:
try {
Class.forName(JDBC_DRIVER);
System.out.println("connecting to database");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("connected to database successfully");
System.out.println("creating table in given database");
// stmt = conn.createStatement();
String sql = "CREATE TABLE newtable "
+ "(id INTEGER not NULL, "
+ "first VARCHAR(255), "
+ "PRIMARY KEY ( id ))";
stmt = conn.prepareStatement(sql);
stmt.executeUpdate(sql);
System.out.println("created table in database");
}
These are just snippets. I am just trying to merge above code.
Help me by telling if this is possible or not and sharing some insights into this.
Multiple connections in a single program, can be created like this
public static void main(String[] args) {
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection con1 = DriverManager.getConnection("jdbc:jtds:sybase://10.159.252.29:4100/fmdb","sa","Changeme_123");
Class.forName(JDBC_DRIVER);
Connection con2 = DriverManager.getConnection(DB_URL, USER, PASS);
///After getting both connections, write your code
String a;
String b;
String c;
Statement stmt= con1.createStatement();
ResultSet rs=stmt.executeQuery("select tbl_alm_log_2000000000.Csn, tbl_alm_log_2000000000.IsCleared, tbl_alm_log_2000000000.Id From fmdb.dbo.tbl_alm_log_2000000000 Where IsCleared = 0");
while(rs.next()) ///If your query result is single row, use if instead of while
{
a = rs.getString(1);
b = rs.getString(2);
c = rs.getString(3);
System.out.println(a+" "+b+" "+c);
}
String sql = "CREATE TABLE newtable " + "(id INTEGER not NULL, " + "first VARCHAR(255), " + "PRIMARY KEY ( id ))";
stmt = con2.prepareStatement(sql);
stmt.executeUpdate(sql);
con1.close();
con2.close();
}catch(Exception e){ System.out.println(e);}
}
}
the suggestion is to divide a complex task into smaller and more simple tasks:
1)create a method readDB(int startReading, int endReading)with return as ResultSet
2)create a method writeDB(ResultSet result)
3)create a method createTableDB()
P.S. readDB is close to your first example and have to return the read of db, writeDB have only to write inside a db some tutorial, and then createTableDB have to make the table on db like you write in your second example.
pseudo final code, in main:
createTableDB();
// it's good to make a loop for next part:
ResultSet read1=readDB(0,200);
writeDB(read1);
ResultSet read2=readDB(200,400);
writeDB(read2);
ResultSet read3=readDB(400,....); //to the end of db
writeDB(read3);
this is a realy simple solution, it is not perfect and can be modified according to your needs.
My database is MySQL run from xampp
I have 3 colums id,nazwa,kwota
I keep getting an error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown
column 'main' in 'field list'
I think problem is with the
String sql = ("SELECT id, nazwa, kwota");
ResultSet rs = stmt.executeQuery(sql);
but I was looking for almost 2 hours and does not seem to find the answer...
Im desperate, thank you
import java.sql.*;
import javax.sql.*;
public class JdbcDriver{
public static void main(String args[]) {
Connection conn = null;
Statement stmt = null;
String username = "wojtek";
String password = "3445222";
String url = "jdbc:mysql://localhost:3306/javatest";
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(url, username, password);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = ("SELECT id, nazwa, kwota");
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String nazwa = rs.getString("nazwa");
int kwota = rs.getInt("kwota");
//Display values
System.out.print("ID: " + id);
System.out.print(", Nazwa: " + nazwa);
System.out.print(", kwota: " + kwota);
}
rs.close();
}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
That's a weird wrong SQL statement as pointed below. It's missing FROM table_name
String sql = ("SELECT id, nazwa, kwota");
It should be
String sql = ("SELECT id, nazwa, kwota FROM your_table_name");
^... missing this part
Table is missing in the statement. Better way is always test the query in the database editor before using it.
We always pass SQL Statement in a String in java. If the Statement is Wrong the java compiler gives us an Exception. Same is the case with you, you have passed statement through string. But you have not specified the table from which you are retriving you data.
Your String is:
String sql = ("SELECT id, nazwa, kwota");
You should write the String as:
String sql = ("SELECT id, nazwa, kwota FROM table");
Here table is your table Name from which you are retriving your data.
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
I am using MySQL Server 5.6, Tomcat 8.0. I can create an SQL input statement that is successful in putting hard coded values into my table but if I try to use a variable instead, it appears as NULL in the table. I have println statements immediately before the SQL statement that show the right value in the variable. My syntax looks right and, as I said, it works for hard coded values.
Please excuse the code formatting. This is supposed to be a quick (HA!) and dirty proof of concept.
Code snippet:
// method to update spice table with input data
public void update()
{
System.out.println("Starting Update");
java.sql.Date useDate = new java.sql.Date(convert(date));
Connection conn = null;
Statement stmt = null;
String sql;
try{
System.out.println("Starting try...");
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Connected database successfully...");
// Execute update
System.out.println("Creating statement...");
stmt = conn.createStatement();
System.out.println("Name is " + name +".");
System.out.println("Name is " + getName() +".");
sql = "INSERT INTO spices VALUES (name, 'location', 'container', 'status', useDate)";
stmt.executeUpdate(sql);
// Clean-up environment
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
System.out.println("errors for JDBC");
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
System.out.println("errors for Class.forName");
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
System.out.println("SQLException - stmt.close()");
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
System.out.println("SQLException - conn.close()");
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
server log showing println output:
2015-05-25 19:37:46 Commons Daemon procrun stdout initialized
Starting Update
Starting try...
Connecting to database...
Connected database successfully...
Creating statement...
Name is chilli.
Name is chilli.
Goodbye!
Table output:
| NULL | location | container | status | NULL |
The first NULL should say "chilli".
Any help would be greatly appreciated - I'm tearing hair here!
kwl
It should be
sql = "INSERT INTO spices VALUES ('"+name+"', 'location', 'container', 'status', '"+useDate+"')";