Is it possible to increment the size of a column (say varchar2(25)) by 50? To be precise, I am not looking for something like this:
ALTER TABLE <Table_name> modify <Column_name> varchar2(75);
Rather, I am inquisitive about something that will increase the size by 50 or some other integer constant without the explicit calculation on the programmer part.
PS: Please comment if I am not clear.
Just to be clear, it appears you're asking for a way to add a fixed value to the column size without knowing what the original size is (hence asking how to add 50 and disallowing setting it directly to 75, which would require knowing it was 25 to start with).
Most databases provide system tables or views which give you the metadata about various objects. For example, DB2/z has sysibm.syscolumns and Oracle has all_tab_columns as shown in this link.
If you wanted to expand the column by 50 without knowing in advance what the size was, you could simply consult the metadata to get the current size and just add 50, constructing a statement to do it for you.
In other words, use something like:
select char_length from all_tab_columns
where owner = '<Table_owner>'
and table_name = '<Table_name>'
and column_name = '<Column_name>'
then extract that number from the recordset, add 50, and use that to dynamically construct and execute an alter table statement, similar to the one in your question that assumes you already know the length you want.
You can also use the user_tab_columns view if you're only concerned with your own tables rather than all those you can see. In that case, you don't need to concern yourself with the where owner = clause.
Although this sample code is specific to the DB2/z metadata, it wouldn't take much to convert it to the corresponding Oracle version:
import java.io.*;
import java.util.*;
import java.sql.*;
class chgcolsz {
public void chgcolsz() {}
public static void main (String args[]) {
Connection conn;
try {
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
conn = DriverManager.getConnection(
"jdbc:db2://MyBox:9999/MyInstance", "Me", "MyPassword");
conn.setAutoCommit (true);
} catch (Exception e) {
System.out.println ("** Error: DB connect: " + e);
e.printStackTrace();
return;
}
String cmd =
"select length from sysibm.syscolumns" +
" where tbcreator = 'PAX'" +
" and tbname = 'XYZZY'" +
" and name = 'COLUMN1'";
ResultSet rs;
try {
Statement sttmnt = conn.createStatement();
rs = sttmnt.executeQuery (cmd);
} catch (Exception e) {
rs = null;
System.out.println ("** Warning: rowset create: '" +
cmd + "': " + e);
e.printStackTrace();
}
int sz = -1;
if (rs != null) {
try {
rs.next();
sz = rs.getInt(1);
rs.close();
} catch (Exception e) {
System.out.println ("** Warning: rowset close: " + e);
e.printStackTrace();
};
}
if (sz != -1) {
System.out.println ("Current size is " + sz);
cmd = "alter table pax.xyzzy" +
" alter column column1" +
" set data type" +
" varchar(" + (sz + 50) + ")";
System.out.println ("Executing: " + cmd);
try {
Statement sttmnt = conn.createStatement();
sttmnt.execute (cmd);
} catch (Exception e) {
System.out.println ("** Warning: table alter: '" +
cmd + "': " + e);
e.printStackTrace();
}
}
try {
conn.close();
} catch (Exception e) {
System.out.println ("** Warning: DB close: " + e);
e.printStackTrace();
};
}
}
You can see from subsequent runs of this program that it's increasing the column width by 50 each time:
pax> java chgcolsz
Current size is 50
Executing: alter table pax.xyzzy alter column column1 set data type varchar(100)
pax> java chgcolsz
Current size is 100
Executing: alter table pax.xyzzy alter column column1 set data type varchar(150)
pax> java chgcolsz
Current size is 150
Executing: alter table pax.xyzzy alter column column1 set data type varchar(200)
Related
I'm using a batch class in EJB to INSERT more than 100 rows in the same commit using the command line executeBatch in the DB2.
When I execute the command shows this error: ERRORCODE=-4229, SQLSTATE=null.
The ID sequence is IDENTITY clause on the CREATE TABLE.
Table:
CREATE TABLE table (col1 INT,
col2 DOUBLE,
col3 INT NOT NULL GENERATED ALWAYS AS IDENTITY)
Does anyone have any idea?
ERROR:
Caused by: nested exception is: com.ibm.db2.jcc.am.BatchUpdateException: [jcc][t4][102][10040][4.24.97] Batch failure. The batch was submitted, but at least one exception occurred in an individual batch member.
Use getNextException() to retrieve exceptions for specific batch elements. ERRORCODE=-4229, SQLSTATE=null
It's not an answer, but a suggestion to handle Db2 exceptions to have an ability to deal with such errors.
If you are unable to rewrite your error handling, the only thing you can to is to enable JDBC trace on the client or/and set the Db2 dbm cfg DIAGLEVEL parameter to 4.
PreparedStatement pst = null;
try
{
pst = ...;
...
int [] updateCounts = pst.executeBatch();
System.out.println("Batch results:");
for (int i = 0; i < updateCounts.length; i++)
System.out.println(" Statement " + i + ":" + updateCounts[i]);
} catch (SQLException ex)
{
while (ex != null)
{
if (ex instanceof com.ibm.db2.jcc.DB2Diagnosable)
{
com.ibm.db2.jcc.DB2Diagnosable db2ex = com.ibm.db2.jcc.DB2Diagnosable) ex;
com.ibm.db2.jcc.DB2Sqlca sqlca = db2ex.getSqlca();
if (sqlca != null)
{
System.out.println("SQLCODE: " + sqlca.getSqlCode());
System.out.println("MESSAGE: " + sqlca.getMessage());
}
else
{
System.out.println("Error code: " + ex.getErrorCode());
System.out.println("Error msg : " + ex.getMessage());
}
}
else
{
System.out.println("Error code (no db2): " + ex.getErrorCode());
System.out.println("Error msg (no db2): " + ex.getMessage());
}
if (ex instanceof BatchUpdateException)
{
System.out.println("Contents of BatchUpdateException:");
System.out.println(" Update counts: ");
System.out.println(" Statement.SUCCESS_NO_INFO: " + Statement.SUCCESS_NO_INFO);
System.out.println(" Statement.EXECUTE_FAILED : " + Statement.EXECUTE_FAILED);
BatchUpdateException buex = (BatchUpdateException) ex;
int [] updateCounts = buex.getUpdateCounts();
for (int i = 0; i < updateCounts.length; i++)
System.out.println(" Statement " + i + ":" + updateCounts[i]);
}
ex = ex.getNextException();
}
}
...
I am writing methods through JDBC to create a table and a sequence to recall in a Trigger, I want to set up an id column which auto-increments before every insert on the table. I succeeded in building both the createTable method and the createSequence method in the DAO, but when I run the method to create the Trigger I got the java.sql.SQLException: Missing IN or OUT parameter at index:: 1
public void createTrigger() {
PreparedStatement ps;
StringBuilder queryTrigger = new StringBuilder();
queryTrigger.append("CREATE OR REPLACE TRIGGER ");
queryTrigger.append(Tables.getInstance().getName() + "_INSERTED\n");
queryTrigger.append("BEFORE INSERT ON " + Tabelle.getInstance().getName());
queryTrigger.append("\nFOR EACH ROW\n");
queryTrigger.append("BEGIN\n");
queryTrigger.append("SELECT " + Tables.getInstance().getName() + "SEQ.NEXTVAL\n");
queryTrigger.append("INTO :new.id\n");
queryTrigger.append("FROM dual;\n ");
queryTrigger.append("END;\n");
queryTrigger.append("/\n");
queryTrigger.append("ALTER TRIGGER " +Tabelle.getInstance().getName() + "_INSERTED ENABLE\n");
queryTrigger.append("/\n");
String stringQueryTrigger = queryTrigger.toString();
Connection conn = JDBCUtility.openConnection();
try {
ps = (PreparedStatement) conn.prepareStatement(stringQueryTrigger);
ps.executeUpdate();
ps.close();
} catch(SQLException e) {
e.printStackTrace();
}
JDBCUtility.closeConnection(conn);}
Here instead the creation of the table does actually work even if I don't
write the classic lines with parametrized "?" for the preparedStatement.setString(index, String)
public void createTable(Columns c) {
PreparedStatement ps;
StringBuilder query = new StringBuilder();
query.append("CREATE TABLE " + Tabelle.getInstance().getName() + "(");
query.append(Columns.getInstance().getColumnName() + " ");
query.append(Columns.getInstance().getDataType());
if(Columns.getInstance().isNullOrNot() == true) {
query.append(" NOT NULL");
}
else {
query.append("");
}
if(Columns.getInstance().isPrimaryKeyOrNot() == true) {
query.append(" PRIMARY KEY)");
}
else {
query.append(")");
}
String queryToString = query.toString();
Connection conn = JDBCUtility.openConnection();
try {
ps = (PreparedStatement) conn.prepareStatement(queryToString);
ps.executeUpdate();
ps.close();
} catch(SQLException e) {
e.printStackTrace();
}
JDBCUtility.closeConnection(conn);
}
//EDIT
turns out that is enough to substitute the PreparedStatement with a simple Statement, to get rid of the indexes mechanism and get the DB to accept the query
I would suggest creating an auto-increment sequnce in oracle that can be used for all ids and just add the string id.NextVal to the string query
What I mean is:
Rem in oracle create sequence
CREATE SEQUENCE ID
START BY 1
INCREMENT 1
// in java to execute query
String query = "INSERT INTO TABLE VALUES(ID.NEXTVAL);" ;
//rest of code
Hello guys whenever I try to delete a row using a radiobutton, I get both try and catch messages, when it is supposed to be just 1 of them, I have this code
Here's my calling button method
if(request.getParameter("btnEliminar") != null)
{
String value;
int codParse;
OC_DAO objDAO = new OC_DAO();
valor = request.getParameter("rbSel");
codParse = Integer.parseInt(valor);
objDAO.DeleteRow(codParse);
}
Here's my java code
public void DeleteRow(int codDet)
{
try
{
cn = Conexion.getConexion();
pt = cn.prepareStatement("DELETE "
+ "FROM detalleProd "
+ "WHERE codDet = ?");
pt.setInt(1, codDet);
pt.executeUpdate();
System.out.println("ROW DELETED ON CODDET: " + codDet);
rs.close();
pt.close();
cn.close();
}
catch(Exception exc)
{
System.out.println("Error while deleting");
System.out.println(exc.toString());
}
}
And here's my log
Información: ROW DELETED ON CODDET: 48
Información: Error while deleting
Información: java.lang.NullPointerException
The reason is due to rs.close();, you have not set value of rs,it's null and can not be closed,you just need to remove this line of code.
Your code seems very strange,I do not have see where you declare rs,it will compile error in your IDE.
I am trying to pass value from Jcombobox and I used Like Operator in order to retrieve data from Database ..
I need to retrieve all data related to a chosen month from combobox
String sql = "SELECT * FROM Treatment WHERE Treatment_Date LIKE '?%'";
try {
ps = con.prepareStatement(sql);
ps.setString(1, cmb.getSelectedItem().toString());
rs = ps.executeQuery();
table_PatuentReg.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
String sql = "SELECT * FROM Treatment WHERE Treatment_Date LIKE '"+cmb.getText().toString()+"%'";
Use this format.
this will help more...
You need to change the query and add the % in the prepared statement value where we are setting the value for string.
String sql = "SELECT * FROM Treatment WHERE Treatment_Date LIKE ?";
try {
ps = con.prepareStatement(sql);
ps.setString(1, cmb.getSelectedItem().toString()+"?");
rs = ps.executeQuery();
table_PatuentReg.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
Try putting it directly in the ? mark sign, like so
String sql = "SELECT * FROM Treatment WHERE Treatment_Date LIKE '"+cmb.getSelectedItem().toString()+"%'";
try {
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
table_PatuentReg.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
I'm trying to delete all data from Table where index=Textbox1.Text and idnmb=Textbox2.Text
When I remove this part + "AND id_nmb = " + data2 it works but not what I want.
I have this code :
private void button1_Click(object sender, RoutedEventArgs e)
{
var data1 = this.textBox1.Text;
var data2 = this.textBox2.Text;
OleDbCommand cmd = new OleDbCommand("DELETE FROM Table WHERE index = " + data1 + "AND idnmb = " + data2 , con);
cmd.Connection = con;
int temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
MessageBox.Show("OK !");
}
else
{
MessageBox.Show("Some error !");
}
}
}
It gives me this message : No value given for one or more required parameters.
Any idea how to solve this ?
The short answer is likely that you need a space before AND in your string. It looks like you assume numbers will be entered in each of the textboxes, but you don't enforce that, so different errors may occur depending on the content of those textboxes.
The longer answer is DON'T DO IT THIS WAY! You're opening up your code to SQL Injection attacks. Use parameterized queries instead as shown in this reference.