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
Related
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 1 year ago.
I'm trying to create to the table into my database. And this is my code..
(my db name is koneksi, and my table name is table)
private void datatable(){
DefaultTableModel tbl = new DefaultTableModel();
tbl.addColumn("Nomor Induk");
tbl.addColumn("Nama Siswa");
tbl.addColumn("Kelas");
tbl.addColumn("Jenis Kelamin");
tbl.addColumn("Nilai Harian");
tbl.addColumn("Nilai UTS");
tbl.addColumn("Nilai UAS");
tbl.addColumn("Nilai Akhir");
tbl.addColumn("Grade");
tbl.addColumn("Keterangan");
table.setModel(tbl);
try{
Statement panggil = (Statement)koneksi.gettConnection().createStatement();
ResultSet res = panggil.executeQuery("select * from table");
while(res.next()){
tbl.addRow(new Object[]{
res.getString("nis"),
res.getString("nama"),
res.getString("kelas"),
res.getString("jeniskelamin"),
res.getString("harian"),
res.getString("uts"),
res.getString("uas"),
res.getString("akhir"),
res.getString("grade"),
res.getString("ket"),
});
table.setModel(tbl);
}
}catch (Exception e)
{
JOptionPane.showMessageDialog(rootPane, e.getMessage());
}
}
And this is my koneksi.java code..
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class koneksi {
static Connection sambung;
public static Connection gettConnection(){
try{
sambung=DriverManager.getConnection("jdbc:mysql://localhost/koneksi","root","");
}catch (Exception e){
JOptionPane.showConfirmDialog(null,"Connection Failed");
}return sambung;
}
}
I have to trying since 5 days ago, but I'm still getting this error..
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'table' at line 1.
I still learn Java basicly. I have been to asked my software engineering teacher at school how to fix this problem, but we still can't fix it. I'm waiting for ur solution answer, thanks. :)
table is a reserved keyword. See https://mariadb.com/kb/en/reserved-words/
You must either rename your table to some word that is not a reserved keyword, or else delimit it with back-ticks:
select * from `table`
I'm new to JDBC and Java.
I'm coming from Javascript and Typescript background. I decided to learn JDBC with Oracle by creating a small basic project.
I'm using JDK 8. I'm following this study material: TutorialsPoint-PreparedStatement. I figured out that problem is with my DataService.
Here's my DataService class:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DataService {
Connection con;
PreparedStatement pstmt;
static String branch_name="";
static LocalDate branch_created_on;
static String branch_pulled_from="";
DataService() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","scott");
}
catch(Exception e){
System.out.println(e);
}
}
public void getValue() {
branch_name=AddNewBranchRecord.branchNameTextField.getText();
branch_created_on=AddNewBranchRecord.datePicker1.getValue();
branch_pulled_from=(String) AddNewBranchRecord.combo_box_1.getValue();
}
public void putValue() {
System.out.println("Branch name: "+branch_name);
System.out.println("Branch created on: "+branch_created_on);
System.out.println("Branch pulled from: "+branch_pulled_from);
}
public void insertRecord() {
System.out.println("Adding a record...");
getValue();
try {
String sql;
sql = "insert into mybranches values (branch_name, branch_created_on, branch_pulled_from);";
pstmt = con.prepareStatement(sql);
} catch (SQLException ex) {
Logger.getLogger(DataService.class.getName()).log(Level.SEVERE, null, ex);
}
pstmt .close();
}
}
I'm sure there's something that I missed out.
I'm not getting any error or exception but no row is inserted in the database.
I cross checked with select * from mybranches.
However, the same code works perfectly if I use the normal Statement.
You create the PreparedStatement but you don't use it.
A prepared statement is there to e.g. insert different values into a table multiple times.
You create the PreparedStatement once like you would execute a normal Statement and include ? instead of the values that differ.
If you want to execute it, you have to set the values (the ?s will be replaced with them) by using the setXXX(int,Type) methods and then execute it with .execute().
As pointed out in the comments of the question, the SQL code is not valid. The sql code prepared statement is just like the sql code of a regular statement but the values that change all the time are replaced by ?.
The SQL code of the prepared statement would be something like that:
INSERT INTO mybranches VALUES (?,?,?)
If you want to use the PreparedStatement, you could set the values like that:
pstmt.setString(1,branch_name);
pstmt.setObject(2,branch_created_from);
pstmt.setString(3,branch_pulled_from);
Finally, execute it with
pstmt.execute();
Note that (as I already said) you should create the PreparedStatement once and not every time you execute the insertRecord() method and in that method, you should just call the setXXX methods and the execute() method.
The PreparedStatement (and the Connection object) should be closed when you don't need it anymore.
Also, as #TT. suggests in the comments, you should specify the columns in an INSERT statement. It would be something like
INSERT INTO mybranches (name,createdFrom,pulledFrom) VALUES (?,?,?)
This question already has answers here:
Variable column names using prepared statements
(7 answers)
Using Prepared Statements to set Table Name
(8 answers)
Closed 4 years ago.
Very first question here so I apologize for any mistakes and imperfections.
Basically there are three files, my main method tech_supportv1, login_controller containing a class used to store a bunch of methods, and login.java, a javabean.
The point is to check if a certain row exists on the tech_support database. To do so I'm trying to use the code below. (db_util and type are classes containing connection data, they are tested and they work).
ISSUE: the data from the main method seems not be pasted into the string in the appropriate placeholders, and an error is returned. (Of course if I manually enter the strings instead of using placeholders, everything works just fine.)
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''technicians' WHERE 'techID' LIKE 16' at line 1
I tired to look at the mariaDB docs but all the other syntax provided yields the same results.
So this the main method.
public class Tech_support_v1 {
public static void main(String[] args) {
System.out.println("Start.");
login bean = new login();
bean.setTable("technicians");
bean.setColumn("techID");
bean.setID(16);
login_controller.select(bean);
}
}
This is the select method (with bean as argument, login is the Javabean class).
public static boolean select(login bean) {
String sql = "SELECT * FROM ? WHERE ? LIKE ?";
ResultSet rs;
try (
Connection conn = db_util.getConn(db_type.MYSQL);
PreparedStatement stmt = conn.prepareStatement(sql);
) {
stmt.setString(1, bean.getTable());
stmt.setString(2, bean.getColumn());
stmt.setInt(3, bean.getID());
rs = stmt.executeQuery();
if (rs.next()) {
System.out.println("Y");
return true;
} else {
System.err.println("N");
return false;
}
} catch (Exception e) {
System.err.println(e);
return false;
}
}
I won't include the bean class because it's literally only three variables with the relative set/get methods. Also the database runs with MariaDB, and is MySQL.
Thanks to everyone in advance.
You have multiple problems with your code :-)
First, you can't set table or column names with "setString" in a Prepared Statement!
See this Question: How to use a tablename variable for a java prepared statement insert
Second, as Daniel Pereira pointed out: You are trying to use a "like" Statement with "setInt"! See: https://dev.mysql.com/doc/refman/8.0/en/pattern-matching.html
You are comparing with LIKE but you are setting an Int. Change the LIKE to = and see if it works.
Try doing something like this:
String sql="SELECT * FROM :table ";
try (
Connection conn = db_util.getConn(db_type.MYSQL);
PreparedStatement stmt = conn.prepareStatement(sql);
)
{
String query = StringUtils.replace(sql, ":table", bean.getTable());
stmt.executeQuery(query);
}
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.
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.