Is there a way to add dynamically columns and column names to an existing table using jdbc?
For example:
If NumberOfColumns = 3, I want the column names to be "Column1", Column2", "Column3".
I tried to add dynamically some columns with the name of iterator just for testing my code but it gives me an SQL syntax error.
Below are some parts of my code I just described. If I remove the whole loop, the code works like a charm.
public class something {
//Some Variables Declaration///
//Number of columns in test table//
int NumberOfColumns = 3;
public static void main(String args[]) {
//..... SOME CODE....//
//Create database//
sql = "CREATE DATABASE mydb";
stmt.executeUpdate(sql);
//Create test table//
sql = "CREATE TABLE mydb.table "
+ "(id INTEGER not NULL ";
stmt.executeUpdate(sql);
//Add columns dynamically//
for (int i = 0; i < NumberOfColumns; i++) {
sql = "ALTER TABLE mydb.test ADD'" + i + "' VARCHAR(30)";
stmt.executeUpdate(sql);
}
stmt.executeUpdate(sql);
}
}
First of all you should to delete your stmt.executeUpdate(sql); after your loop, this can make a problem,
change this lines:
for (int i = 0; i < NumberOfColumns; i++) {
sql = "ALTER TABLE mydb.test ADD'" + i + "' VARCHAR(30)";
stmt.executeUpdate(sql);
}
stmt.executeUpdate(sql);
just with this:
for (int i = 0; i < NumberOfColumns; i++) {
colname = "Column" + i;
sql = "ALTER TABLE mydatabase.table ADD " + colname + " VARCHAR(30)";
stmt.executeUpdate(sql);
}
Because you can will get an error that the 3ed column exist
also the name of column not need 'id' you just need to remove the two quots
Here is an exemple can solve your problem:
Requires that you initialize a driver so you can open a communications channel with the database, after create your database your tables and your columns,
package DataBase;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class createdatabase {
//Number of columns in test table//
private static int NumberOfColumns = 3;
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "root";
static final String PASS = "mypass";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "CREATE DATABASE mydatabase";
stmt.executeUpdate(sql);
sql = "CREATE TABLE mydatabase.table (id INTEGER not NULL)";
stmt.executeUpdate(sql);
String colname;
for (int i = 0; i < NumberOfColumns; i++) {
colname = "Column" + i;
sql = "ALTER TABLE mydatabase.table ADD " + colname + " VARCHAR(30)";
stmt.executeUpdate(sql);
}
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Exception = " + e);
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException se2) {
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
System.out.println("Exception" + se);
}
}
}
}
Hope this can help you
You need a space after the keyword ADD in the alter statement. I would also recommend prefixing the column name rather than just using a number.
Can you post the SQL error as well, to help clarify what the error actually is.
Related
im learning now mysql and jdbc and i got home work im trying to add a foreign key and i cant understant what is this exeption this is my code please if someone can explain me what the problem it will realy help me
package jdbc;
import java.sql.*;
public class JDBC_HW {
public static void main(String[] args) throws ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/newdatabase", "root", "admin")) {
try (Statement statement = connection.createStatement()) {
String newTable = "CREATE TABLE jb_student (id int not null auto_increment, name varchar(500), grade int, PRIMARY key(id));";
statement.executeUpdate(newTable);
}
String insertStudents = "INSERT INTO newdatabase.jb_student "
+ "( name, grade)"
+ " VALUES( ?, ?);";
try (PreparedStatement preparedStatement = connection.prepareStatement(insertStudents)) {
for (int i = 0; i < 100; i++) {
preparedStatement.setString(1, "student" + i);
preparedStatement.setInt(2, i * 100);
preparedStatement.executeUpdate();
}
}
String printTable = "select * from newdatabase.jb_student";
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(printTable);
while (resultSet.next()) {
System.out.print(resultSet.getInt(1));
System.out.print(" ");
System.out.print(resultSet.getString(2));
System.out.print(" ");
System.out.println(resultSet.getInt(3));
}
}
String update = "UPDATE jb_student SET name = 'nikita', grade = 100 where id = 1;";
try (Statement statement = connection.createStatement()) {
int countUpdates = statement.executeUpdate(update);
System.out.println("updated rows : " + countUpdates);
}
String searchByName1 = "select * from jb_student where name like '%1';";
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(searchByName1);
while (resultSet.next()) {
System.out.print(resultSet.getInt(1));
System.out.print(" ");
System.out.print(resultSet.getString(2));
System.out.print(" ");
System.out.println(resultSet.getInt(3));
}
}
String newTable = "CREATE TABLE jb_courses (id int not null auto_increment, name varchar(500), PRIMARY key(id));";
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(newTable);
}
String insertCourses = "INSERT INTO newdatabase.jb_courses "
+ "(name)"
+ " VALUES(?);";
try (PreparedStatement preparedStatement = connection.prepareStatement(insertCourses)) {
for (int i = 0; i < 5; i++) {
preparedStatement.setString(1, "course" + " " + i);
preparedStatement.executeUpdate();
}
}
String addColumn = "ALTER TABLE jb_student ADD COLUMN course_id int not null AFTER id;";
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(addColumn);
}
String addFk = "ALTER TABLE jb_student add FOREIGN KEY (course_id) REFERENCES jb_courses (id);";
try(Statement statement = connection.createStatement()){
statement.executeUpdate(addFk);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
im sitting on this long time and cant resolve this exeption i tryied everithing i could think of
and im still getting this exeption :
java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`newdatabase`.`#sql-12f0_21`, CONSTRAINT `jb_student_ibfk_1` FOREIGN KEY (`course_id`) REFERENCES `jb_courses` (`id`))
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1333)
at com.mysql.cj.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2106)
at com.mysql.cj.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1243)
at jdbc.JDBC_HW.main(JDBC_HW.java:92)
im braking my head on this thank you for helping
I create this code for get column name in sql databases. But now I ant to modify above code for get all table data with column name. Then get all data and convert to jsonarray and pass. How I modify this code for get all table data with column name.
#Override
public JSONArray getarray(String sheetName) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
con.setAutoCommit(false);
PreparedStatement pstm = null;
Statement stmt = null;
//-----------------------Drop earliye table -------------------------------------------------------------
try {
String sqldrop = "select COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='" + sheetName.replaceAll(" ", "_") + "'";
System.out.println(sqldrop);
PreparedStatement mypstmt = con.prepareStatement(sqldrop);
ResultSet resultSet = mypstmt.executeQuery();
JSONArray jsonArray = new JSONArray();
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 0; i < total_rows; i++) {
String columnName = resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase();
Object columnValue = resultSet.getObject(i + 1).toString().replaceAll("_", " ");
// if value in DB is null, then we set it to default value
if (columnValue == null) {
columnValue = "null";
}
/*
Next if block is a hack. In case when in db we have values like price and price1 there's a bug in jdbc -
both this names are getting stored as price in ResulSet. Therefore when we store second column value,
we overwrite original value of price. To avoid that, i simply add 1 to be consistent with DB.
*/
if (obj.has(columnName)) {
columnName += "1";
}
obj.put(columnName, columnValue);
}
jsonArray.put(obj);
}
mypstmt.close();
con.commit();
return jsonArray;
} catch (Exception e) {
System.out.println("There is no exist earlyer databases table!..... :( :( :( **************** " + sheetName.replaceAll(" ", "_"));
}
//----------------------------------------------------------------------------
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (SQLException ex) {
Logger.getLogger(PassArrayDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("%%%%%%%%%%");
return null;
}
My target is get all data with column name and above data pass html page as a json. So if you have any method for get all data with column name is suitable for me.
// code starts here
// This method retrieves all data from a mysql table...
public void retrieveAllData( String host, String user, String pass, String query) {
JTextArea textArea = new JTextArea();
try(
Connection connection = DriverManager.getConnection( host, user, pass )
Statement statement = connection.createStatement()
ResultSet resultSet = statement.executeQuery(query)) {
ResultSetMetaData metaData = resultSet.getMetaData();
int totalColumns = metaData.getColumnCount();
for( int i = 1; i <= totalColumns; i++ ) {
textArea.append( String.format( "%-8s\t", metaData.getColumnName(i) ) );
}
textArea.append( "\n" );
while( resultSet.next() ) {
for( int i = 1; i <= totalColumns; i++ ) {
Object object = resultSet.getObject(i).toString();
textArea.append( String.format("%-8s\t", object) );
}
textArea.append( "\n" );
}
}
}
I have a database schema that its name is "Navid"
there is many tables in this schema.
definitely each table, has some columns.
what I need is a java class that:
Connect to my database.
Have a method that loop on all tables
2-1. Have an inner loop to define all columns of the table.
Make create table query statement .(I want to create the same table in another database).
Execute that query.
I write some code but I do not know what to do next.
public class automateExport {
static String value;
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// ResultSet rs = null;
String table_name;
String column_name;
String tableName = null;
StringBuilder sb = new StringBuilder(1024);
Connection DB2 = getConnection();
String sql = "SELECT TABSCHEMA,TABNAME,COLNAME FROM SYSCAT.COLUMNS WHERE TABSCHEMA NOT LIKE 'SYS%'";
PreparedStatement mainStmt = DB2.prepareStatement(sql);
ResultSet rs = mainStmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
/* while(rs.next()){
table_name = rs.getString(2);
// for(int i = 1; i <= 1; i ++){
column_name = rs.getString(3);
System.out.println("SSS::::: " + table_name + " " + column_name );
// }
*/
for (int i = 1; i <= rows; i++) {
while (rs.next()) {
table_name = rs.getString(2);
if (i > 1) {
sb.append(", ");
}
column_name = rs.getString(3);
String columnType = rsmd.getColumnTypeName(i);
sb.append(" ").append(column_name).append(" ").append(columnType);
int precision = rsmd.getPrecision(i);
if (precision != 0) {
sb.append("( ").append(precision).append(" )");
}
} // for columns
sb.append(" ) ");
String sql2 = sb.toString();
PreparedStatement m = DB2.prepareStatement(sql);
m.executeQuery();
System.out.println(sb.toString());
}
}
private static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("COM.ibm.db2os390.sqlj.jdbc.DB2SQLJDriver");
Connection connection
= DriverManager.getConnection("jdbc:db2://localhost:50000/navid", "navid", "oracle");
return connection;
}
}
gurus,
I am new to Java SQL, and need some help.
I'm trying to get a parameter from MS SQL Server 2008. The data is definitely there - it is a current and valid DB, and I'm trying to use the users records to get cridentials for another application.
I asserted the following query:
String query = "SELECT [USER].qc_number FROM [USER] WHERE "[USER].login_name = '"
+ userNameInput + "' AND [USER].password = '" + passWordInput + "';";
Where userNameInput and passWordInput are received from the user. The URL, query and driver class are definitely correct: I checked the DB schema both from the application and from the server views. Furthermore, I verified all the Exceptions systems by changing parameters one by one, resulting in correct Exceptions messages. However, I get a resultSet with 1 column and 0 rows.
The code is below:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class trOdbc
{// database URL
final String DB_URL = "***";
final String Class_URL = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private Connection connection = null; // manages connection
private Statement statement = null; // query statement
private ResultSet resultSet = null; // manages results
private Boolean connectedToDatabase = false;
// ----------------------------------------------------------
public void createJdbcConnection()
{ // connect to database books and query database
if (connectedToDatabase)
{ return; }
try
{ // connectedToDatabase is false - establish the connection
Class.forName(Class_URL);
connection = DriverManager.getConnection
(DB_URL, "***", "***" );
statement = connection.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
connectedToDatabase = true;
}
catch (SQLException ex)
{ System.out.println ("SQL Exception in connection establishment: " + ex); }
catch (ClassNotFoundException ex)
{ System.out.println ("Class not found exception in query process: " + ex); }
}
// ----------------------------------------------------------
public String [][] processJdbcQuery (String query)
{
createJdbcConnection ();
if (!connectedToDatabase)
{ return null; }// the connection wasn't established
try
{// query database
resultSet = statement.executeQuery(query);
int columns = resultSet.getMetaData().getColumnCount();
int rows = 0;
if (resultSet != null)
{
resultSet.beforeFirst();
resultSet.last();
rows = resultSet.getRow();
}
String [][] tempData = new String[rows][columns];
resultSet.beforeFirst();
rows = 0;
while (resultSet.next())
{
for (int x = 1; x <= columns; x++)
{
tempData [rows][x - 1] = resultSet.getString (x);
}
rows++;
}
CloseJdbcConnection ();
return tempData;
}
catch (SQLException ex)
{
System.out.println ("SQL Exception in query process: " + ex);
CloseJdbcConnection ();
return null;
}
} // end processJdbcQuery
// ----------------------------------------------------------
public void CloseJdbcConnection()
{
if ( connectedToDatabase )
{// close Statement and Connection. resultSet is closed automatically.
try
{
statement.close();
connection.close();
connectedToDatabase = false;
}
catch (SQLException ex)
{ System.out.println ("SQL Exception in connection closure: " + ex); }
} // end if
} // end method CloseJdbcConnection
} // end class trOdbc
Why don't you use Prepared Statement instead ?
Here is a good tutorial for using prepared statement in java
In your case it would be :
String query = "SELECT [USER].qc_number FROM [USER] " +
"WHERE [USER].login_name = ? AND [USER].password = ?;";
And then set it with different values each time you execute it like :
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, userNameInput);
ps.setString(2, passWordInput);
resultSet = ps.executeQuery();
I'm using MySQL commands via JDBC (Java) to make changes to my database. I have implemented the following method to return the values of a column. The goal is to have the location in the column (row) correspond with their location in the array (index). This works with String columns, but with numerical columns, the ResultSet seems to place them in ascending order, thus making their positioning in the returned String array not reflect their positioning in the column. 'rs' is a ResultSet reference variable.
public String[] getColumnContents(String tableName, String columnName) {
String sql = "SELECT " + columnName + " FROM " + tableName;
String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];
try {
rs = statement.executeQuery(sql);
for (int counter = 0; rs.next(); counter++) {
results[counter] = rs.getString(columnName);
}
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}
It's as simple as adding an ORDER BY clause to the SQL command. Here's my working method:
public String[] getColumnContents(String tableName, String columnName) {
String sql = "SELECT " + columnName + " FROM " + tableName + " ORDER BY " + columnName1 + " ASC, " + columnName2 + " ASC";
String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];
try {
rs = statement.executeQuery(sql);
for (int counter = 0; rs.next(); counter++) {
results[counter] = rs.getString(columnName);
}
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}