I created a database with one table in MySQL:
CREATE DATABASE iac_enrollment_system;
USE iac_enrollment_system;
CREATE TABLE course(
course_code CHAR(7),
course_desc VARCHAR(255) NOT NULL,
course_chair VARCHAR(255),
PRIMARY KEY(course_code)
);
I tried to insert a record using Java:
// STEP 1: Import required packages
import java.sql.*;
import java.util.*;
public class SQLInsert {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/iac_enrollment_system";
// Database credentials
static final String USER = "root";
static final String PASS = "1234";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
Scanner scn = new Scanner(System.in);
String course_code = null, course_desc = null, course_chair = null;
try {
// STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// STEP 3: Open a connection
System.out.print("\nConnecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println(" SUCCESS!\n");
// STEP 4: Ask for user input
System.out.print("Enter course code: ");
course_code = scn.nextLine();
System.out.print("Enter course description: ");
course_desc = scn.nextLine();
System.out.print("Enter course chair: ");
course_chair = scn.nextLine();
// STEP 5: Excute query
System.out.print("\nInserting records into table...");
stmt = conn.createStatement();
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
System.out.println(" SUCCESS!\n");
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt != null)
conn.close();
} catch(SQLException se) {
}
try {
if(conn != null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Thank you for your patronage!");
}
}
The output appears to return successfully:
But when I select from MySQL, the inserted record is blank:
Why is it inserting a blank record?
no that cannot work(not with real data):
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
change it to:
String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
"VALUES (?, ?, ?)";
Create a PreparedStatment with that sql and insert the values with index:
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate();
this can also be done like this if you don't want to use prepared statements.
String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"
Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.
This should work for any table, instead of hard-coding the columns.
//Source details
String sourceUrl = "jdbc:oracle:thin:#//server:1521/db";
String sourceUserName = "src";
String sourcePassword = "***";
// Destination details
String destinationUserName = "dest";
String destinationPassword = "***";
String destinationUrl = "jdbc:mysql://server:3306/db";
Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);
Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);
PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT * FROM src_table ");
ResultSet rs = sourceStatement.executeQuery();
rs.setFetchSize(1000); // not needed
ResultSetMetaData meta = rs.getMetaData();
List<String> columns = new ArrayList<>();
for (int i = 1; i <= meta.getColumnCount(); i++)
columns.add(meta.getColumnName(i));
try (PreparedStatement destStatement = destConnection.prepareStatement(
"INSERT INTO dest_table ("
+ columns.stream().collect(Collectors.joining(", "))
+ ") VALUES ("
+ columns.stream().map(c -> "?").collect(Collectors.joining(", "))
+ ")"
)
)
{
int count = 0;
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
destStatement.setObject(i, rs.getObject(i));
}
destStatement.addBatch();
count++;
}
destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed
System.out.println("done " + count);
}
There is a mistake in your insert statement chage it to below and try :
String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";
Related
I am using JDBC and mySQL to do an application for a family. After logging in into the system, the user can register for a family account. By SQL statement, I want to ensure that the input they keyed in is not repeated and they can only register when the database have a NRIC of them individually. I am working with JDBC and implementing the SQL statement in Java also. For now my problem is the system does not validate the input the user keys in and let's the information to be passed to database easily. Would appreciate some help!
*NRIC = Identity Card No
Snapshots of Database:
User Database
Family Account Database
Code
public boolean regFamily(FamilyAccount myFam, Customer myCust) throws Exception {
int fid = 0;
try {
String selectStatement2 = "SELECT * from familyok.user where nric = ? and familyid is NOT NULL ";
PreparedStatement pStmt2 = con.prepareStatement(selectStatement2);
pStmt2.setString(1, myCust.getNric());
ResultSet rs2 = pStmt2.executeQuery();
if (rs2.next()) {
String insertStatement = "Insert into familyok.familyaccount (familyname, fnric1, fnric2, fnric3)";
insertStatement = insertStatement + "values (?,?,?,?)";
PreparedStatement prepStmt = con.prepareStatement(insertStatement);
prepStmt.setString(1, myFam.getFamilyname());
prepStmt.setString(2, myFam.getFnric1());
prepStmt.setString(3, myFam.getFnric2());
prepStmt.setString(4, myFam.getFnric3());
int status = prepStmt.executeUpdate();
if (status != 0) {
String selectStatement = "SELECT fid FROM familyok.familyaccount WHERE fnric1=?";
PreparedStatement pStmt = con.prepareStatement(selectStatement);
pStmt.setString(1, myFam.getFnric1());
ResultSet rs = pStmt.executeQuery();
if (rs.next()) {
System.out.println(rs.getInt("fid") + "\t");
fid = rs.getInt("fid");
String updateStatement = "update familyok.user set familyid=?, familyname1=? where nric in (?,?,?)";
PreparedStatement preparedStmt = con.prepareStatement(updateStatement);
preparedStmt.setInt(1, fid);
preparedStmt.setString(2, myFam.getFamilyname());
preparedStmt.setString(3, myFam.getFnric1());
preparedStmt.setString(4, myFam.getFnric2());
preparedStmt.setString(5, myFam.getFnric3());
int status2 = preparedStmt.executeUpdate();
System.out.println("update=" + preparedStmt.toString());
if (status2 != 0) {
System.out.println("Family Account Created");
return true;
}
}
}
}
else
{
System.out.println("Can't Register");
return false;
}
} catch (Exception ex) {
throw new Exception("Error: " + ex.getMessage());
}
return false;
}
I've read H2 docs about storing objects in database. There is special SQL type OTHER and methods setObject and getObject. I've tried this code:
PreparedStatement statement = null;
try {
statement = connection.prepareStatement("CREATE TABLE PUBLIC.foo (name VARCHAR(64) NOT NULL, data OTHER NULL);");
statement.execute();
} finally {
statement.close();
}
statement = null;
try {
statement = connection.prepareStatement("INSERT INTO PUBLIC.foo (name, data) VALUES(?,?);");
statement.setString(1, "lololo");
statement.setObject(2, new String[]{"foo", "bar"});
statement.execute();
}finally {
statement.close();
}
But I've got the exception:
org.h2.jdbc.JdbcSQLException: Ше�тнадцатирична� �трока �одержит неше�тнадцатиричные �имволы: "(foo, bar)"
Hexadecimal string contains non-hex character: "(foo, bar)"; SQL statement:
INSERT INTO PUBLIC.foo (name, data) VALUES(?,?) -- (?1, ?2) [90004-191]
What is wrong?
I believe this is what you were look for (Even I was).
You just need to create a column in your table with type as 'other'.
See 'create table testobj2(obj other)'
Look at my Sample code :
static String DB_DRIVER = "org.h2.Driver";
static String DB_CONNECTION = "jdbc:h2:./test2";
static String DB_USER = "";
static String DB_PASSWORD = "";
public static void benchmarkH2Inserts() {
try {
Class.forName(DB_DRIVER);
Connection dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
String createQry = "create table testobj2(obj other)";
String insertQuery = "insert into testobj2(obj) values(?)";
String selectQuery = "select * from testobj2";
// dbConnection.setAutoCommit(false);
dbConnection.prepareStatement(createQry).executeUpdate();
long lStartTime = System.nanoTime();
for(int i=0; i<10000; i++) {
dbConnection.setAutoCommit(false);
CloudElement_Circuit obj = new CloudElement_Circuit();
obj.setNrm8DesignId(1230L);
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertQuery);
preparedStatement.setObject(1,obj);
preparedStatement.execute();
dbConnection.commit();
}
long lEndTime = System.nanoTime();
long output = lEndTime - lStartTime;
System.out.println("benchmarkH2Inserts() : Elapsed time in nanoseconds: " + output);
System.out.println("benchmarkH2Inserts() : Elapsed time in milliseconds: " + output / 1000000);
//Selecting
PreparedStatement preparedStatement = dbConnection.prepareStatement(selectQuery);
ResultSet rs = preparedStatement.executeQuery();
while(rs.next()) {
CloudElement_Circuit obj = (CloudElement_Circuit) rs.getObject("obj");
System.out.println("Fetched Object : " + obj.getNrm8DesignId());
}
dbConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Note that 'CloudElement_Circuit' is a Serialized class.
Look at 'OTHER Type' here : http://www.h2database.com/html/datatypes.html
H2 Example : https://www.javatips.net/blog/h2-database-example
Try this approach
List<String> genre = new ArrayList<String>();
String comma="";
StringBuilder allGenres = new StringBuilder();
for (String g: genre) {
allGenres.append(comma);
allGenres.append(g);
comma = ", ";
}
Then you can pass it like this
preparedStmt.setString (2, allGenres.toString());
This question already has answers here:
Java JDBC MySQL exception: "Operation not allowed after ResultSet closed"
(2 answers)
Closed 6 years ago.
I am trying to run following code but getting error:
SQL Exception thrown: java.sql.SQLException: Operation not allowed
after ResultSet closed.
How to resolve this error? I need two result sets for my application.
public static void main(String[] args) {
String connectionUrl = "jdbc:mysql://127.0.0.1:3306/test";
String dbUser = "root";
String dbPwd = "Syntel#92";
Connection conn;
ResultSet rs, res1 = null;
Statement stmt = null;
int rowcount = 0;
// String queryString = "create table job_status_table as select j1.job_id,s1.Source_ID,s1.Source_name from JOb_list j1,SOURCE_DETAILS s1 where s1.Source_ID = j1.Source_ID";
String queryString = "create table job_status_table as select source_id,source_name from source_details";
String addcolumn = "alter table job_status_table add column Source_rowcount int";
String fetchdata = "Select Source_name from job_status_table";
try {
conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
stmt = conn.createStatement();
// get record count from table job_status_table1
// stmt.executeQuery("select count() from job_status_table1");
// create table
stmt.executeUpdate(queryString);
System.out.println("Table created in the database");
stmt.executeUpdate(addcolumn);
System.out.println("alter table");
rs = stmt.executeQuery(fetchdata);
System.out.println("fetch data");
while (rs.next()) {
String table_count = null;
String table_name = null;
table_name = rs.getString("Source_name");
System.out.println(table_name);
// table_name = rs.getString("Source_name");
//System.out.println(table_name);
//rs.close();
table_count = "select count(*) from " + table_name;
//table_count = "select count(*) from " + table_name;
//rs.close();
// res1 = stmt.executeQuery(table_count);
res1 = stmt.executeQuery(table_count);
//System.out.print(res1);
if (res1.next()) {
rowcount = res1.getInt(1);//res1.getInt(1);
System.out.println("Result set values" + rowcount);
} else {
System.out.println("value is not present in resultset");
}
System.out.println("Get Row Count");
System.out.println(table_count);
// int cnt = rcnt(table_count);
String updaterow = "update job_status_table set Source_rowcount ="
+ rowcount
+ " where Source_name = '"
+ table_name
+ "'";
System.out.println("updateoutput" +stmt.executeUpdate(updaterow));
System.out.println("Update Complete");
}
/* if (conn != null) {
rs.close();
res1.close();
stmt.close();
conn.close();
conn = null;
}
*/
}
catch (SQLException sqle) {
System.out.println("SQL Exception thrown: " + sqle);
}
}
}**
You could try this:
First copy the ResultSet rs in an ArrayList and close it.
Iterate over the ArrayList and close res1 before the update.
And I don't think the else with "value is not present in resultset" is reachable, but if you should set the rowcount to 0.
EDIT
After reading the referenced question the second time:
The problem is the reusing of stmt for res1 and the update
I am facing error java.sql.SQLFeatureNotSupportedException in my prepare statement. I am using Mysql database.
Below is my code.
class tmp {
public static void main(String arg[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/sample", "root", "root");
PreparedStatement pst = conn
.prepareStatement("select * from userinfo where firstname in(?)");
String[] Parameter = { "user1", "Administrator" };
Array sqlArray = conn.createArrayOf("VARCHAR", Parameter);
pst.setArray(1, sqlArray);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
For Mysql -
Setting array is not possible in Mysql.
Instead of that you can form a query for (?,?,..) in the loop and same way for setting values.
String[] Parameter = { "user1", "Administrator" };
String query = "select * from userinfo where firstname in (";
String temp = "";
for(i = 0; i < Parameter.length; i++) {
temp += ",?";
}
temp = temp.replaceFirst(",", "");
temp += ")";
query = query + temp;
PreparedStatement pst = conn.prepareStatement(query);
so query becomes
select * from userinfo where firstname in (?,?)
and pass values also using loop.
For Oracle -
ArrayDescriptor arrayDescriptor = ArrayDescriptor.createDescriptor("CHAR_ARRAY", conn);
String[] Parameter = { "user1", "Administrator" };
java.sql.Array sqlArray = new oracle.sql.ARRAY(arrayDescriptor, conn, content);
.
.
pstmt.setArray(1, sqlArray);
Error message is very clear. And MySQL does not support custom data types.
Currently MySQL is supporting only:
Numeric Type
Date and Time Type
String Type
Or, you can use each of the input values as a set of values of IN function in MySQL.
Change your JAVA code as follows:
StringBuilder sbSql = new StringBuilder( 1024 );
sbSql.append( "select * from userinfo where firstname in(" );
for( int i=0; i < Parameter.length; i++ ) {
if( i > 0 ) sbSql.append( "," );
sbSql.append( " ?" );
} // for
sbSql.append( " )" );
PreparedStatement pst = conn.prepareStatement( sbSql.toString() );
for( int i=0; i < Parameter.length; i++ ) {
pst.setString( i+1, Parameter[ i ] );
} // for
ResultSet rs = pst.executeQuery();
Convert List to a comma separated String and use it.
Class Tmp {
public static void main(String arg[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/sample", "root", "root");
// Consider this list is already constructed
List<String> parameter = new ArrayList<String>();
parameter.add("user1");
parameter.add("Administrator");
String parameterStr = "'" + String.join("','", parameter) + "'";
PreparedStatement pst = conn.prepareStatement("select * from userinfo where firstname in(" + parameterStr + ")");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I'm trying this tutorial code and it seems to print out my database from MySQL twice. It comes from this while loop below:
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getString(2);
String user = resultSet.getString("myuser");
String email = resultSet.getString("email");
String website = resultSet.getString("webpage");
String summary = resultSet.getString("summary");
Date date = resultSet.getDate("datum");
String comment = resultSet.getString("comments");
System.out.println("User: " + user);
System.out.println("Email: " + email);
System.out.println("Website: " + website);
System.out.println("Summary: " + summary);
System.out.println("Date: " + date);
System.out.println("Comment: " + comment);
}
That loop prints out twice. If I put a break statement at the end of the loop, it still prints the first row of my database twice. I think it has something to do with resultSet.next(). Here is the full code below:
package de.vogella.mysql.first;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
public class MySQLAccess {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public void readDataBase() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection("jdbc:mysql://localhost/feedback?"
+ "user=sqluser&password=sqluserpw");
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement
.executeQuery("select * from FEEDBACK.COMMENTS");
writeResultSet(resultSet);
// PreparedStatements can use variables and are more efficient
preparedStatement = connect
.prepareStatement("insert into FEEDBACK.COMMENTS values (default, ?, ?, ?, ? , ?, ?)");
// "myuser, webpage, datum, summary, COMMENTS from FEEDBACK.COMMENTS");
// Parameters start with 1
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "TestEmail");
preparedStatement.setString(3, "TestWebpage");
preparedStatement.setDate(4, new java.sql.Date(2009-12-11));
preparedStatement.setString(5, "TestSummary");
preparedStatement.setString(6, "TestComment");
preparedStatement.executeUpdate();
preparedStatement = connect
.prepareStatement("SELECT myuser, email, webpage, datum, summary, COMMENTS from FEEDBACK.COMMENTS");
resultSet = preparedStatement.executeQuery();
writeResultSet(resultSet);
// Remove again the insert comment
preparedStatement = connect
.prepareStatement("delete from FEEDBACK.COMMENTS where myuser= ? ; ");
preparedStatement.setString(1, "Test");
preparedStatement.executeUpdate();
resultSet = statement
.executeQuery("select * from FEEDBACK.COMMENTS");
writeMetaData(resultSet);
} catch (Exception e) {
throw e;
} finally {
close();
}
}
private void writeMetaData(ResultSet resultSet) throws SQLException {
// Now get some metadata from the database
// Result set get the result of the SQL query
System.out.println("The columns in the table are: ");
System.out.println("Table: " + resultSet.getMetaData().getTableName(1));
for (int i = 1; i<= resultSet.getMetaData().getColumnCount(); i++){
System.out.println("Column " +i + " "+ resultSet.getMetaData().getColumnName(i));
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getString(2);
String user = resultSet.getString("myuser");
String email = resultSet.getString("email");
String website = resultSet.getString("webpage");
String summary = resultSet.getString("summary");
Date date = resultSet.getDate("datum");
String comment = resultSet.getString("comments");
System.out.println("User: " + user);
System.out.println("Email: " + email);
System.out.println("Website: " + website);
System.out.println("Summary: " + summary);
System.out.println("Date: " + date);
System.out.println("Comment: " + comment);
}
}
// You need to close the resultSet
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (Exception e) {
}
}