how to insert data in my sql using else if in jsp - java

Hi I'm trying to insert data in mysql but my page throw no response!
pease can anyone help me about it?
Code runs but println() is not displaying
//<%#page import= "java.sql.*"%>
// <%# page import="java.util.Random"%>
<%
String dt = request.getParameter("dt");
String particular = request.getParameter("vas");
String emp = request.getParameter("emp");
String amt = request.getParameter("amt");
int amnt = Integer.parseInt(amt);
//Class.forName("com.mysql.jdbc.Driver");
//Connection con = //DriverManager.getConnection("jdbc:mysql://localhost:3306/furqania", "root", "khan");
Statement st = con.createStatement();
if (particular == "amanatraseedi")
{
Random rnd = new Random();
int rn = rnd.nextInt(9000) + 10000;
String sr = "AMT" + rn;
// int i = st.executeUpdate("insert into amanatraseedi='"+particular+"'(transactionid,dt,amount,empid) values('" + sr + "','" + dt + "','" + amnt + "','" + emp + "')");
if (i > 0) {
out.println("Amanat raseedi successful!");
} else {
out.println("something went wrong!");
}
}
else if (particular == "amadhisab")
{
Random rnd = new Random();
int rn = rnd.nextInt(9000) + 10000;
String sr = "AMD" + rn;
int i = st.executeUpdate("insert into amadhisab='"+particular+"' (transactionid,dt,amount,empid) values('" + sr + "','" + dt + "','" + amnt + "','" + emp + "')");
if (i > 0) {
out.println("Amad hisab successful!");
}
else {
out.println("something went wrong!");
}
}
st.close();
con.close();
%>

Related

java - after search of database, print the full row of the result

I got a code, which is searching a whole database. Everything works fine, the only problem is, that I would like to post the whole tuple with integers and chars and so on.
package src;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.regex.Pattern;
/*
PATTERN MATCHING
*/
public class BigSearch {
public static void main(String[] args) {
try {
String keyword;
String schema = "public";
Boolean caseAware = true;
System.out.println("Insert the term we shall look for in the database.");
Scanner s = new Scanner(System.in);
keyword = s.nextLine();
System.out.println("Do you want the search to be case sensitve "
+ "\n1 - case sensitive"
+ "\n0 - case insensitive");
int caseAwareInt = s.nextInt();
while (caseAwareInt != 0 && caseAwareInt != 1) {
System.out.println("You need to enter 1 or 0. Enter again!");
caseAwareInt = s.nextInt();
}
if (caseAwareInt == 1) {
caseAware = true;
} else if (caseAwareInt == 0) {
caseAware = false;
}
System.out.println("Your search is now case ");
if (caseAware) {
System.out.println("sensitive!");
}
if (!caseAware) {
System.out.println("insensitive!");
}
String like = "";
if (caseAware) {
like = "LIKE";
} else {
like = "ILIKE";
}
Connectivity connectivity = new Connectivity();
conn = connectivity.getConnection();
Statement stmt = conn.createStatement();
Statement stmt2 = conn.createStatement();
Statement stmt3 = conn.createStatement();
Statement stmt4 = conn.createStatement();
Statement stmt5 = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM pg_catalog.pg_tables WHERE schemaname = '" + schema + "';");
ResultSet tablenames = stmt2.executeQuery("SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '" + schema + "';");
rs.next();
int counttables = rs.getInt(1);
System.out.println("Tabellen im Schema: " + counttables);
int appearance = 0;
int diftables = 0;
for (int i = 0; i < counttables; i++) {
tablenames.next();
ResultSet columnnames = stmt3.executeQuery("SELECT * " +
"FROM information_schema.columns " +
"WHERE table_schema = '" + schema +
"' AND table_name = '" + tablenames.getString(1) +
"' AND data_type = 'character varying'");
ResultSet rss = stmt4.executeQuery("SELECT COUNT(*) " +
"FROM information_schema.columns " +
"WHERE table_schema = '" + schema +
"' AND table_name = '" + tablenames.getString(1) +
"' AND data_type = 'character varying'");
rss.next();
int countcolumns = rss.getInt (1);
System.out.println("Spalten in der Tabelle " + tablenames.getString(1) + ": " + countcolumns);
int count = 0;
for (int i2 = 0; i2 < countcolumns; i2++) {
columnnames.next();
columnnames.getString(1);
System.out.println("Spaltenname: " + columnnames.getString(1));
System.out.println("Tabelle: " + tablenames.getString(1));
ResultSet containsString;
containsString = stmt5.executeQuery("SELECT * "
+ "FROM " + tablenames.getString(1)
+ " WHERE " + columnnames.getString(1) + " " + like + " '%" + keyword + "%'");
while (containsString.next()) {
System.out.println(containsString.getString(1) + " -- contains your keyword");
appearance++;
count ++;
}
}
if (count > 0) {
diftables ++;
}
}
System.out.println("The keyword was found " + appearance + " times in " + diftables + " different tales.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I think the problem is the following code:
while (containsString.next()) {
System.out.println(containsString.getString(1) + " -- contains your keyword");
appearance++;
count ++;
}
So there I am saying getString(1), but I would like to print the full row and because all table have different variable types and different numbers of it, I can't say getString 1, 2, 3, and so on. .getRow doens't work is well.
Any ideas?
There is no way to get all values at once. You need to get them yourself column-by-column. You could use getObject and let the default toString() of that object handle it. The other option is to use the ResultSetMetaData to get the right type of processing, but this might be too complex for your needs.
The getRow doesn't work, because it "Retrieves the current row number.".
Some JDBC drivers will support getString for most datatypes and handle the conversion for you.

Inserting records into an Oracle DB using Java

I am getting a missing comma error and I can't seem to figure out what could be causing it, any help would be appreciated.
Table create SQL:
CREATE TABLE APPOINTMENTS (APP_ID NUMBER(38) NOT NULL, I_ID NUMBER(38), DATE_TIME VARCHAR2(50), INSPECTION_TYPE VARCHAR2(30), PRICE VARCHAR2(10), HST VARCHAR2(10), TOTAL VARCHAR2(10), CLIENT_NAME VARCHAR2(40), CLIENT_NUMBER VARCHAR2(15), CLIENT_EXT VARCHAR2(10), CLIENT_EMAIL VARCHAR2(50), CLIENT_NAME2 VARCHAR2(40), CLIENT_NUMBER2 VARCHAR2(15), CLIENT_EXT2 VARCHAR2(10), CLIENT_EMAIL2 VARCHAR2(50), ADDRESS VARCHAR2(100), INTERSECTION VARCHAR2(100), CITY VARCHAR2(40), AGENT_ID NUMBER(38), REF_SOURCE VARCHAR2(30), BUILDING_TYPE VARCHAR2(30), SQUARE_FEET NUMBER(38), LIST_PRICE VARCHAR2(15), LOCKBOX VARCHAR2(40), VACANT VARCHAR2(10), NOTES VARCHAR2(255), BILL_TO VARCHAR2(20), PICTURES_REQUESTED VARCHAR2(10), FLAG VARCHAR2(10), APPROVED VARCHAR2(10), BUILDING_PREMIUM VARCHAR2(10), TRAVEL_PREMIUM VARCHAR2(10), SIZE_PREMIUM VARCHAR2(10), HOLIDAY_PREMIUM VARCHAR2(10), MISC_PREMIUM VARCHAR2(10), INSPECTOR_PAID VARCHAR2(10), COMPANY VARCHAR2(10) NOT NULL, SUGGESTED_RETAIL VARCHAR2(10), SUGGESTED_HST VARCHAR2(10), SUGGESTED_TOTAL VARCHAR2(10), PRIMARY KEY (APP_ID));
Java code to insert and execute:
dc.query = "INSERT INTO HR.APPOINTMENTS (APP_ID,I_ID, DATE_TIME,INSPECTION_TYPE, PRICE, HST, TOTAL, CLIENT_NAME, CLIENT_NUMBER, CLIENT_EXT, CLIENT_EMAIL,CLIENT_NAME2, "
+ "CLIENT_NUMBER2, CLIENT_EXT2, CLIENT_EMAIL2, ADDRESS, INTERSECTION, CITY, AGENT_ID, REF_SOURCE, BUILDING_TYPE, SQUARE_FEET, LIST_PRICE, LOCKBOX, VACANT,"
+ "NOTES, BILL_TO, PICTURES_REQUESTED, FLAG, APPROVED, BUILDING_PREMIUM, TRAVEL_PREMIUM, SIZE_PREMIUM, HOLIDAY_PREMIUM, MISC_PREMIUM, INSPECTOR_PAID,"
+ "COMPANY, SUGGESTED_RETAIL, SUGGESTED_HST, SUGGESTED_TOTAL)"
+ ""
+ "VALUES (" + hNum + "," + inspector + ",'" + date1 + "','" + inspectionType + "','" + price + "','" + hst + "','" + total + "','" + clientName + "','" + clientNumber + "','"
+ clientExt + "','" + clientEmail + "','" + clientName2 + "','" + clientNumber2 + "','" + clientExt2 + "','" + clientEmail2 + "','" + address + "','" + cMIntersection
+ "','" + city + "'," + hNum2 + ",'" + rSource + "','" + bType + "', 1000 ,'" + listPrice + "','" + lockbox + "','" + vacant + "','" + sInformation + "','" + billTo + "','"
+ pRequested + "','" + flagged + "', 'No', 'No', '0' , '0', '0', '0', '0', 'No','" + company + "','" + suggestedPrice + "','" + suggestedhst + "','" + suggestedTotal + "')";
dc.rset = dc.stmt.executeQuery(dc.query);
Here is a more generic approach. You just need to worry about class Oracle below and perhaps add some new entries for Factory method as I only defined a couple for you.
I also coded the actual execute for your PreparedStatement in the Row class, however I never tested that far. Let me know if it works for you (Don't forget to set your database credentials and stuff) ...
import java.io.IOException;
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.ArrayList;
import java.util.List;
public class Oracle {
public static void main(String[] args) {
Row row = new Row("OWNERNAME", "TABLENAME");
row.setDummyValues();
// set your individual column values here as you debug ...
System.out.println( row.getPreparedStatement() );
// for(Column column : row.getColumns()) {
// System.out.println("[" + column.name + "][" + column.type + "][" + column.nullable + "[" + column.value + "]");
// }
}
}
class Column {
int position;
String name;
String type;
boolean nullable;
Object value;
public Column(ResultSet resultSet) throws SQLException {
position = resultSet.getInt("COLUMN_ID");
name= resultSet.getString("COLUMN_NAME");
type= resultSet.getString("DATA_TYPE");
nullable= resultSet.getBoolean("NULLABLE");
value = null;
}
}
class DummyValueFactory {
public static Object createDummyValue(String type, boolean nullable) {
Object value = null;
if(!nullable) {
if(type.contains("CHAR")) {
value = "ABC";
}
else if(type.contains("NUMBER")) {
value = new Integer("123");
}
else if(type.contains("TIMESTAMP")) {
value = new java.sql.Timestamp(System.currentTimeMillis());
}
else {
throw new RuntimeException("CANNOT BUILD A DUMMY VALUE FOR " + type);
}
}
return value;
}
}
class Row {
String owner;
String table;
List<Column> columns = new ArrayList<Column>();
public Row(String ownerName, String tableName) {
owner = ownerName;
table = tableName;
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(getMetaDataQuery());
while(resultSet.next()) {
columns.add(new Column(resultSet));
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if(resultSet != null) {
resultSet.close();
}
if(statement != null) {
statement.close();
}
if(connection != null) {
connection.close();
}
}
catch (SQLException e) {
statement = null;
connection = null;
}
}
}
public void setDummyValues() {
for(Column column: columns) {
column.value = DummyValueFactory.createDummyValue(column.type, column.nullable);
}
}
public List<Column> getColumns() {
return columns;
}
public Column getColumn(String columnName) {
Column foundColumn = null;
for(Column column: columns) {
if(column.name.equals(columnName)) {
foundColumn = column;
break;
}
}
return foundColumn;
}
public boolean setColumn(String columnName, Object value) {
boolean result = false;
for(Column column: columns) {
if(column.name.equals(columnName)) {
column.value = value;
result = true;
break;
}
}
return result;
}
private final String getMetaDataQuery() {
String SQLString = "SELECT COLUMN_ID,\n";
SQLString += " COLUMN_NAME,\n";
SQLString += " DATA_TYPE,\n";
SQLString += " NULLABLE\n";
SQLString += "FROM ALL_TAB_COLUMNS\n";
SQLString += "WHERE OWNER = '" + owner + "'\n";
SQLString += " AND TABLE_NAME = '" + table + "'\n";
SQLString += "ORDER BY COLUMN_ID";
return SQLString;
}
public String getPreparedStatement() {
int counter = 0;
String SQLString = "INSERT INTO " + owner + "." + table + "(\n";
for(Column column : columns) {
if(counter++ > 0) {
SQLString += ", ";
}
SQLString += "\t" + column.name + "\n";
}
SQLString += ") VALUES (\n";
counter = 0;
for(int index = 0; index < columns.size(); index++) {
if(counter++ > 0) {
SQLString += ", ";
}
SQLString += "\t?\n";
}
SQLString += ")";
return SQLString;
}
public void executeInsert() {
Connection connection = null;
PreparedStatement preparedStatement = null;
String SQLString = getPreparedStatement();
try {
connection = getConnection();
preparedStatement = connection.prepareStatement(SQLString);
for(int index = 0; index < columns.size(); index++) {
preparedStatement.setObject(index, columns.get(index).value);
}
preparedStatement.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if(preparedStatement != null) {
preparedStatement.close();
}
if(connection != null) {
connection.close();
}
}
catch (SQLException e) {
preparedStatement = null;
connection = null;
}
}
}
private static final Connection getConnection() throws ClassNotFoundException, SQLException, IOException {
String user = "username";
String password = "password";
String server = "server";
int port = 1234;
String sid = "database";
Connection connection = null;
String url = "jdbc:oracle:thin:#" + server + ":" + port + ":" + sid;
Class.forName("oracle.jdbc.driver.OracleDriver");
java.util.Properties info = new java.util.Properties();
info.put ("user", user);
info.put ("password", password);
info.put ("useFetchSizeWithLongColumn", "true");
connection = DriverManager.getConnection(url, info);
return connection;
}
}

error in java update

if (e.getSource() == btn_updt) {
try {
String str = "img";
int max_avail;
double price;
Frame f = new Frame();
Connection con;
DriverManager
.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:dsnproj", "", "");
Statement s = con.createStatement();
// int mno=Integer.parseInt(txt_contcno.getText());
price = Double.parseDouble(txt_price.getText());
max_avail = Integer.parseInt(txt_qty_avl.getText());
String qry_up = "update category set prod_name='"
+ txt_pro_nm.getText() + "',desc='"
+ txt_pro_desc.getText() + "',photo='" + str
+ "',max_quan_avail=" + max_avail + ",cur_price="
+ price + ",per='" + ch_weight.getSelectedItem()
+ "' where p_name='" + ch_pro_nm.getSelectedItem()
+ "'";
System.out.println(qry_up);
s.execute(qry_up);
System.out.println("updated");
// JOptionPane.showMessageDialog(f,
// "Updates Successfully : ","A plain message",JOptionPane.PLAIN_MESSAGE);
} catch (Exception ae) {
System.out.println(ae.getLocalizedMessage());
}
return result;
}
and i got error as:
update category set prod_name='jjhhj',desc='jjjh',photo='img',max_quan_avail=88,cur_price=99.0,per='piece' where p_name='brush' [Microsoft][ODBC Microsoft Access Driver] Syntax error in UPDATE statement.
please help me...
Since DESC is a keyword, you must surround it with [].
Use this for your query:
String qry_up = "update category set prod_name='"
+ txt_pro_nm.getText() + "',[desc]='"
+ txt_pro_desc.getText() + "',photo='" + str
+ "',max_quan_avail=" + max_avail + ",cur_price="
+ price + ",per='" + ch_weight.getSelectedItem()
+ "' where p_name='" + ch_pro_nm.getSelectedItem()
+ "'";

java database function removed - still executing

I have a java web application that I removed a function from the code and yet the database entries that this function writes are still being written to the database.
Inside the IssueWarrant function there is a call to insertWarrantFee that has been commented out.
private void issueWarrant(String CasePrefix, String CaseNumber, String HearingType, String Suspend)
{
int i = 0, intDivision = 0, pos = 0;
String SummSeq = getSummSeq(CasePrefix, CaseNumber);
String Charges = getCharges(CasePrefix, CaseNumber, HearingType);
boolean isVacated = false, isHearingFound = false;
NextBWNumber warrNbr = new NextBWNumber();
String WarrantNumber = warrNbr.getNextBWNumber();
String warrStatus = warrNbr.getNextBWNStatus();
String HearingDesc = "", Division = "";
isVacated = getVacatedStatus(CasePrefix, CaseNumber, HearingType);
isHearingFound = getHearingStatus (CasePrefix, CaseNumber, HearingType);
HearingDesc = getFormatToday() + " " + getHearingDesc(HearingType);
if (HearingDesc.length() > 30)
{
HearingDesc = HearingDesc.substring(0,30);
}
Division = getHearingJudge(CasePrefix,CaseNumber,HearingType);
intDivision = Integer.parseInt(Division);
if (intDivision < 10)
{ Division = "0" + Division; }
Statement localstmt = null;
String localqueryString;
localqueryString = "INSERT INTO " + library7 + "CMPBWPND" +
" (CASPRE, CASNUM, DEFSEQ, CHGSEQ, SUMSEQ, STSCOD, STSDAT," +
" STATUT, CHGABV, BWNBR, JUDCOD, PRVFLG, CT2FLG, DIVISN, BNDAMT," +
" BTYPE, CMNT, CUSER, TUSER, LUPDAT, SCRDAT, STATSDAT, SUMCRDAT, LUPDATE )" +
" VALUES ('" + CasePrefix + "', " + CaseNumber + ", 1, " + Charges.substring(i, i + 1) +
", " + SummSeq + ", 9, " + getShortDate() + ", 'RCP 12-A TA', 'WARRANT', '" +
WarrantNumber + "', " + intDivision + ", 'N', 1, '" + Division + "', " +
BondAmt + ", '" + BondType + "', '" + HearingDesc + "', 'TAAD', 'TAAD', " +
getShortDate() + ", " + getShortDate() + ", " + getLongDate() + ", " + getLongDate() +
", " + getLongDate() + ")";
try
{
if (!isVacated && isHearingFound)
{
localstmt = conn.createStatement();
localstmt.executeUpdate(localqueryString);
localstmt.close();
StatusMsg = "Client No Show-WI";
}
if (isVacated)
{
StatusMsg = "Client Vacated Case";
}
if (!isHearingFound)
{
StatusMsg = "Client Hearing Missing";
}
} catch (SQLException e)
{
System.out.println("IssueWarr - Error in IssueWarrant");
e.printStackTrace();
ReturnInfo = "Issuing Warrants Failed.";
success = false;
}finally
{
try
{
if (!localstmt.isClosed())
{
localstmt.close();
}
} catch (SQLException sql2)
{
System.out.println("Error trying to close connections. Exception: " + sql2.getMessage());
}
}
**//insertWarrantFee(CasePrefix, CaseNumber, SummSeq, WarrantNumber);**
updateHearingRecord(CasePrefix, CaseNumber, HearingType, Charges.substring(i, i + 1), Suspend);
for ( i = 1; i < Charges.length(); i++ )
{
insertBWPTFRecord(CasePrefix, CaseNumber, SummSeq, Charges.substring(i, i + 1));
}
if (!success)
{
StatusMsg = "Client Iss. Warrant Failure";
}
}
Here is the code that the insertWarrantFee called before it was commented out:
private void insertWarrantFee(String CasePrefix, String CaseNumber, String SummSeq, String WarrantNumber)
{
Statement localstmt = null;
String localqueryString;
ResultSet localrSet = null;
String feeAmt = null;
localqueryString = "SELECT AUTO$$ FROM " + library3 + "CMPDKTTP WHERE DKTTYP = 'W'";
try
{
localstmt = conn.createStatement();
localrSet = localstmt.executeQuery(localqueryString);
while (localrSet.next())
{
feeAmt = localrSet.getString("AUTO$$");
}
localstmt.close();
localrSet.close();
} catch (SQLException e)
{
System.out.println("IssueWarr - Error in Insert Warrant Fee SQL1");
e.printStackTrace();
ReturnInfo = "Issuing Warrants Failed.";
success = false;
}finally
{
try
{
if (!localstmt.isClosed())
{
localstmt.close();
}
} catch (SQLException sql2)
{
System.out.println("Error trying to close connections. Exception: " + sql2.getMessage());
}
}
localqueryString = "INSERT INTO " + library7 + "CMPBWTRN"
+ " (CASPRE, CASNUM, DEFSEQ, SUMSEQ, BWNBR, FEEAMT, DKTTYP, TUSER, LUPDAT)"
+ " VALUES ('" + CasePrefix + "', " + CaseNumber + ", 1, " + SummSeq + ", '" + WarrantNumber
+ "', " + feeAmt + ", 'W', 'TAAD', " + getShortDate() + ")";
try
{
localstmt = conn.createStatement();
localstmt.executeUpdate(localqueryString);
localstmt.close();
} catch (SQLException e)
{
System.out.println("IssueWarr - Insert Warrant Fee SQL2");
e.printStackTrace();
ReturnInfo = "Issuing Warrants Failed.";
success = false;
}finally
{
try
{
if (!localstmt.isClosed())
{
localstmt.close();
}
} catch (SQLException sql2)
{
System.out.println("Error trying to close connections. Exception: " + sql2.getMessage());
}
}
}
So even though the line that called insertWarrantFee is commented out a record is still being inserted into CMPBWTRN.
Any ideas how this could happen? The developer is indicating it could be a tomcat connection cache issue? Any other suggestion beside magical code?
Thanks!
Leslie
A couple of things to try:
Make sure you've redeployed the application and have restarted Tomcat. Check the timestamp of the deployed class in question.
Clean Tomcat's tmp and work directories
Open the deployed Java class using a decompiler to see whether the removed code is still in there.
Add a logging (or System.out.println) statement to the method that's commented out, and to the method calling it. See whether one or both are printed after redeploying the changes.

java-mysql program

i have a table - emp_details in mysql
i want to seatch an employ's id number in java.
if it is in the table , then show all the details of employee.
otherwise display an error message.
how i do this
Using JDBC
Here is an example You can build your solution from it.
Statement stmt = null;
String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from " + dbName + ".COFFEES";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID + "\t" + price + "\t" + sales + "\t" + total);
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
stmt.close();
}
ResultSet rs1=stmt.executeQuery("SELECT * FROM employee_details where Employee_ID='"+strEmpId+"'");
if(rs1.next()) {
System.out.println("Emp ID : " + rs1.getString(1));
System.out.println("Emp Name : " + rs1.getString(2));
System.out.println("Emp Salary : " + rs1.getString(3));
} else {
System.out.println("Emp ID not found");
}
If you want to know more about SQL just go through HERE

Categories

Resources