Access mysql database in eclipse using java - java

I created a simple mysql database table using following query:
CREATE TABLE customer(
name varchar(20),
C_ID int NOT NULL AUTO_INCREMENT,
address varchar(20),
email varchar(20),
PRIMARY KEY(C_ID)
);
Now I want to insert values to this table. My client like this:
package com.orderdata.ws;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import com.mysql.jdbc.Statement;
public class OrderData {
public static void main(String[] args)throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/orderdata","root","chathura");
Statement stmt = (Statement) con.createStatement();
String insert = "INSERT INTO customer(name,C_ID,address,email) VALUES (a,5,b,c)";
stmt.executeUpdate(insert);
}
}
But this gives an exception "Exception in thread "main" 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 '(a,5,b,c)' at line 1............"
How can I insert data using eclipse???

When inserting varchar text to MySQL tables, you need to surround it in single quotes like this:
String insert = "INSERT INTO customer(name,C_ID,address,email) VALUES ('a',5,'b','c');";

Access databases need ";" at the end of sql command.
String insert = "INSERT INTO customer(name,C_ID,address,email) VALUES ('a',5,'b','c');";
Edit: And you need to put text data into query like this
VALUES ('a',5,'b','c')
You may need to "escape" ' (quote) characters. I dont know how to do this in java, maybe like this:
VALUES (\'a\',5,\'b\',\'c\')

Related

Copying the data from one table to other table in oracle database using Java

I am new to Java and
I have a table name TABLE1 having column names NAME, ROLL.
CREATE TABLE TABLE1(NAME VARCHAR2(4), ROLL NUMBER(3));
INSERT INTO TABLE1 VALUES ('SAMY', 101);
INSERT INTO TABLE1 VALUES ('TAMY', 102);
INSERT INTO TABLE1 VALUES ('JAMY', 103);
INSERT INTO TABLE1 VALUES ('RAMY', 104);
I have an other table name TABLE2 having column names NAME, ROLL.
CREATE TABLE TABLE1(NAME VARCHAR2(4), ROLL NUMBER(3));
We need to write a Java program to migrate the data from TABLE 1 to TABLE2 in oracle and print the result in console.
I am using Oracle SQL developer.
I have written a Java program but not sure whether it is accurate or not.
java.lang.Class;
java.sql.Connection;
java.sql.DriverManager;
java.sql.ResultSet;
java.sql.Statement;
public class JDBCDemoConnection
{
public static void main(String[] args)
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = null;
connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "username", "password");
Statement smt = connection.createStatement();
String sql = "INSERT INTO TABLE2 (NAME,ROLL)" + "SELECT NAME, ROLL FROM TABLE1";
int i = smt.executeUpdate(sql);
System.out.println(i+ " row is inserted into the table");
connection.close();
}
catch(Exception E)
{
System.out.println(E);
}
}
}
The problem is with the SQL query you are using. After concatenation, the query looks like INSERT INTO TABLE2 (NAME,ROLL) SELECT NAME, ROLL FROM TABLE1 which is not a valid SQL statement.
Simply make use of SELECT INTO statement to copy data from one table into a new table.
Statement smt = connection.createStatement();
String sql = "SELECT NAME, ROLL INTO TABLE2 FROM TABLE1";
boolean result = smt.execute(sql);

Can not create database jdbc [duplicate]

This question already has answers here:
CREATE DATABASE query using java jdbc and prepared statement returns syntax error [duplicate]
(2 answers)
Closed 4 years ago.
I'm trying to create a database with java jdbc with a method so i'm passing the name type string of database as argument to database but i'm facing an issue which is 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 ''Algebra'' at line 1
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DbTest {
private Connection connection;
public void createDb(String name) throws SQLException {
connection = DriverManager.getConnection
("jdbc:mysql://localhost/?user=root&password=root");
String createDbSql = "CREATE DATABASE IF NOT EXISTS ?";
PreparedStatement createDbStat = connection.prepareStatement(createDbSql);
createDbStat.setString(1,name);
createDbStat.executeUpdate();
}
DbTest() {
try {
createDb("Algebra");
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new DbTest();
}
}
When you use createDbStat.setString(1, name); it will create a query like this :
CREATE DATABASE IF NOT EXISTS 'databasename'
//----------------------------^____________^
And this is a wrong syntax, the correct should be :
CREATE DATABASE IF NOT EXISTS databasename
to solve your problem you can just use :
String createDbSql = String.format("CREATE DATABASE IF NOT EXISTS `%s`", name);
// ^^^^
PreparedStatement createDbStat = connection.prepareStatement(createDbSql);
//createDbStat.setString(1,name); no need for this
createDbStat.executeUpdate();
For security reason
Just for security reason, and to avoid SQL Injection make sure that your database name match this:
if(name.matches("^[a-zA-Z_][a-zA-Z0-9_]*$")){
//Correct name
}
for more details read this Check for valid SQL column name
You can't bind your parameter (1) to the database name-
you'll have to use string concatenation in this case.
Your question is also similar to
How to use a tablename variable for a java prepared statement insert
and
CREATE DATABASE query using java jdbc and prepared statement returns syntax error

Selenium with postgreSQL [duplicate]

This question already has answers here:
Cannot simply use PostgreSQL table name ("relation does not exist")
(18 answers)
I keep getting the error "relation [TABLE] does not exist"
(1 answer)
Closed 2 years ago.
I'm trying to connect Selenium with Postgres and the following error is shown:
FAILED: selectQuery org.postgresql.util.PSQLException: ERROR: relation
"login" does not exist
My code is below:
package Posgress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.testng.annotations.Test;
#Test public class PosgressTest {
public static void selectQuery() throws SQLException, ClassNotFoundException {
//Load MySQL JDBC Driver
Class.forName("org.postgresql.Driver");
Connection connection =
DriverManager
.getConnection("jdbc:postgresql://localhost:5432/DIC","postgres", "root");
Statement st = connection.createStatement();
System.out.println("Connection");
String selectquery = "Select * from Login";
System.out.println("Connection1");
// Executing the SQL Query and store the results in ResultSet
ResultSet rs = st.executeQuery(selectquery);
// While loop to iterate through all data and print results
while (rs.next()) {
System.out.println(rs.getString("username"));
System.out.println(rs.getString("password"));
}
// Closing DB Connection
connection.close();
}
}
I have a table 'Login inside schema "DICschema'. I wrote select query like this also "Select * from DICschema.Login" then also same error
You should rename the table to "login" and the schema to "dicschema", not "Login" and "DICschema". Because the query will ignore the case of text.
The query will be like:
"Select * from dicschema.login"
If you want to keep your schema and table name as it is (not changing the character cases), the following query should work for you.
String selectquery = "SELECT * FROM \"DICschema\".\"Login\" ";
This is because when the string in compiled, it changes to lowercase and it can be avoided by using backslash.
It seems that postgres users are unable to access the DIC schema.
Try to attach the prefix(schema) name to the query.

Get the metadata for prepared statement in java with MySql DB

I want to fetch parameter name and parameter type of given prepared statement. I am using MySQL Database. But when I run my program it is throwing an error:
Exception in thread "main" java.sql.SQLException: Parameter metadata not available for the given statement
at this line
String paramTypeName = paramMetaData.getParameterTypeName(param);
I don't know why this is happening. Please anybody help me if possible.
Here's my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = getMySqlConnection();
Statement st = conn.createStatement();
String query = "select * from survey where id > ? and name = ?";
PreparedStatement pstmt = conn.prepareStatement(query);
ParameterMetaData paramMetaData = pstmt.getParameterMetaData();
if (paramMetaData == null) {
System.out.println("db vendor does NOT support ParameterMetaData");
} else {
System.out.println("db vendor supports ParameterMetaData");
// find out the number of dynamic parameters
int paramCount = paramMetaData.getParameterCount();
System.out.println("paramCount=" + paramCount);
System.out.println("-------------------");
for (int param = 1; param <= paramCount; param++) {
System.out.println("param number=" + param);
String paramTypeName = paramMetaData.getParameterTypeName(param);
System.out.println("param SQL type name=" + paramTypeName);
}
}
pstmt.close();
conn.close();
}
public static Connection getMySqlConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mydb";
String username = "root";
String password = "";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
}
According to this
Should the driver generate simplified parameter metadata for PreparedStatements when no
metadata is available either because the server couldn't support preparing the statement, or
server-side prepared statements are disabled?
You have to set generateSimpleParameterMetadata to true
use a connection string similar to this
jdbc:mysql://localhost:3306/mydb?generateSimpleParameterMetadata=true
MySQL JDBC driver currently does not support it. I am solving the similar issue and came up with the following workaround:
include H2 database in your project (it can also run in embedded mode or in-memory)
translate your MySQL create database script to H2 syntax (or write it in ANSI so it is compatible with both)
compile prepared statements on H2 database first and get metadata from them - H2 database supports this function and SQL query syntax is similar in most cases - then save the obtained meta information for later use
there might be differences in data types, etc, but in general this should give you about 80% match with MySQL without too much hassle
I know it has much caveats, but it might work in some use cases.
Also consider upgrading MySQL database to 5.7, there are some enhancements related to prepared statements which may help, but I am not very deeply knowledgable about those:
http://dev.mysql.com/doc/refman/5.7/en/prepared-statements-instances-table.html
http://dev.mysql.com/doc/refman/5.7/en/prepare.html
You have not set the parameter to the prepared statements, without which you cannot get parameter metadata. so first set the parameter
pstmt.setInt(val)
pstmt.setString(val)
After adding the parameters you can get the meta data about the parameter.
Hope this helps.

Java and Firebird Embedded how to create db?

now i get java.sql.SQLException: No suitable driver found for jdbc:firebirdsql:embedded:f/test.fdb
i included jaybird jars with my project. please help me out
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.firebirdsql.gds.impl.GDSType;
import org.firebirdsql.management.FBManager;
public class FireBirdCreator {
public FireBirdCreator() {
FBManager manager = new FBManager(GDSType.getType("EMBEDDED"));
try {
manager.start();
manager.createDatabase("f:/test.fdb", "sysdba", "masterkey");
manager.stop();
Connection bd = DriverManager.getConnection("jdbc:firebirdsql:embedded:f/test.fdb");
Statement st = bd.createStatement();
st.execute("create table if not exists 'TABLE1' ('name1' int, 'name2' text, 'name3' text);");
st.execute("insert into 'TABLE1' ('name1', 'name2', 'name3') values (1, 'name1', 'name2'); ");
st.execute("insert into 'TABLE1' ('name1', 'name2', 'name3') values (2, 'name3', 'name4'); ");
st.execute("insert into 'TABLE1' ('name1', 'name2', 'name3') values (3, 'name5', 'name6');");
ResultSet rs = st.executeQuery("select * from TABLE1");
while (rs.next())
{
System.out.print (rs.getString(1)+" ");
System.out.print (rs.getString(2)+" ");
System.out.println(rs.getString(3));
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String args[]) {
FireBirdCreator fbc = new FireBirdCreator();
}
}
The error message indicates that the file does not exist. The fact that it shows 'null' instead of the actual filename might be a mismatch between embedded version and Jaybird version.
To create a database you need to use the following code (and handle the exceptions it throws in a correct manner):
FBManager manager = new FBManager(GDSType.getType("EMBEDDED"));
manager.start();
manager.createDatabase("database.fdb", "", "");
manager.stop();
Also be aware that the DDL you are using to create the table is not valid Firebird SQL. You will need to use RECREATE TABLE and Firebird does not have a type called text.
Full disclosure: I am one of the developers of Jaybird (the Firebird JDBC driver).

Categories

Resources