please give me advice! I get form data in servlet and try to update the database, but it doesn't works. There is connection with database (without servlet code any data is properly added in db), but no any exception are thrown. The servlet get parameters - they are available in JSP by EL-expressions. I tried to update the db simply by statement, without using preparedStatement but it didn't help. Here it is the code:
public class ServletClass extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
DBConn dbConn = new DBConn();
String number = req.getParameter("number");
String amount = req.getParameter("amount");
String date = req.getParameter("date");
ArrayList list = dbConn.returnList(number, amount, date);
req.setAttribute("attr", list);
RequestDispatcher requestDispatcher = req.getRequestDispatcher("index.jsp");
requestDispatcher.forward(req, resp);
}
}
public class DBConn {
public ArrayList<InvoicesBean> returnList(String number, String amount, String date) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
ArrayList<InvoicesBean> beanList = new ArrayList<InvoicesBean>();
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ved", "root", "1111");
statement = connection.createStatement();
preparedStatement = connection.prepareStatement("insert into invoices values(?, ?, ?);");
preparedStatement.setString(1, number);
preparedStatement.setString(2, amount);
preparedStatement.setString(3, date);
preparedStatement.executeUpdate();
resultSet = statement.executeQuery("SELECT * FROM invoices;");
while (resultSet.next()){
InvoicesBean invoicesBean = new InvoicesBean();
invoicesBean.setNumber(resultSet.getString("number"));
invoicesBean.setAmount(resultSet.getString("amount"));
invoicesBean.setDate(resultSet.getString("date"));
beanList.add(invoicesBean);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return beanList;
}
}
InvoiceBean-class is just a standard bean class with getters/setters
invoicesBean.setNumber(resultSet.getString("number"));
invoicesBean.setAmount(resultSet.getString("amount"));
invoicesBean.setDate(resultSet.getString("date"));
You can not have the database column names as 'number' or 'date'. they are reserved.
check the column names again.
for checking if this is the error, you can replace the column names by column numbers 1,2,3.
Related
I'm working with two stored procedures in an ASP.NET button function. While I get an error message based on the results that the invoice number is already dispatched from the other stored procedure, it still moves to the other stored procedure and executes it.
If the user gets this error message:
This invoice num was already dispatched!
then it shouldn't move on to this aspect of the function
protected void Button2_Click(object sender, EventArgs e)
{
try
{
for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
{
var row = GridView2.Rows[i];
CheckBox chk = row.FindControl("chkInvoice") as CheckBox;
//CheckBox chk = (CheckBox)GridView2.Rows[i].Cells[0].FindControl("CheckBox3");
if (chk != null && chk.Checked)
{
string strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();
using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
{
objConnection.Open();
using (SqlTransaction transaction = objConnection.BeginTransaction())
{
string SID = GridView2.Rows[i].Cells[3].Text.Trim();
SqlDataReader myReader = null;
using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#invoiceNum", SID);
command.Parameters.AddWithValue("#custPONum", GridView2.Rows[i].Cells[4].Text.Trim());
myReader = command.ExecuteReader();
if (myReader.Read())
{
string invoice1 = (myReader["status"].ToString());
if (invoice1 == "0")
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
}
myReader.Close();
}
}
else if (invoice1=="1")
{
using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#loadSheetNum", txtDispatchNum.Text);
cmd.Parameters.AddWithValue("#invoiceNum", SID);
cmd.Parameters.AddWithValue("#removeUser", lblUsername.Text.Replace("Welcome", ""));
**int a = cmd.ExecuteNonQuery();**
cmd.Dispose();
if (a > 0)
{
dt.Rows.RemoveAt(i);
////Read invoice qty from grid view 2
string invoice = GridView2.Rows[i].Cells[5].Text.ToString();
decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
txtInvoiceTotal.Text = invoiceTotal.ToString();
////Read invoice weight from grid view 2
string weight = GridView2.Rows[i].Cells[6].Text.ToString();
decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
txtQtyWeight.Text = invoiceWeight.ToString();
lblError.ForeColor = Color.Green;
lblError.Text = "Selected record(s) successfully updated";
}
else
{
lblError.ForeColor = Color.Red;
lblError.Text = " Record has not yet been recorded";
}
}
//objConnection.Close();
transaction.Commit();
}
}
}
//Button2.Visible = false;
//showData();
GridView2.DataSource = dt;
GridView2.DataBind();
txtInvoiceCount.Text = dt.Rows.Count.ToString();
}
}
}
catch (Exception ex)
{
if (ex.Message.StartsWith("Violation of PRIMARY KEY constraint"))
{
lblError.ForeColor = Color.Red;
lblError.Text = " This invoice number was remove from dispatch sheet before!!";
}
else
{
// re-throw the error if you haven't handled it
lblError.Text = ex.Message;
throw;
}
}
}
You have a very, very simple logic error, but it is incredibly hard to see because your code is such a mess. Therefore, my answer is:
REFACTOR REFACTOR REFACTOR
It is important to get into the habit of writing short functions and controlling their inputs and outputs. If you don't do this, even a fairly trivial operation like this one gets very confusing and error-prone.
Here is an example of how to organize things. We remove most of the code from the click handler:
protected void DeleteButton_Click(object sender, EventArgs e)
{
for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
{
var row = GridView2.Rows[i];
if (IsChecked(row))
{
var result = ProcessRow(row, i);
DisplayResult(i, result);
}
}
}
Firstly, notice it has a meaningful name. These become very important as your application grows. Also, look how short it is! Where did all the code go? Well, it went into two separate methods, which are now short enough for us to view on one page-- a common requirement that IT organizations impose on their programmers, to avoid spaghetti code.
protected TransactionResult ProcessRow(GridViewRow row, int index)
{
var SID = GridView2.Rows[index].Cells[3].Text.Trim();
var custPONum = GridView2.Rows[index].Cells[4].Text.Trim();
var loadSheetNum = txtDispatchNum.Text;
var removeUser = lblUsername.Text.Replace("Welcome", "");
return ExecuteInvoiceTransaction(SID, custPONum, loadSheetNum, removeUser);
}
And
public void DisplayResult(int rowIndex, TransactionResult result)
{
switch result
{
case TransactionResult.Success:
dt.Rows.RemoveAt(rowIndex);
DisplayTotals(rowIndex);
DisplaySuccess("Selected record(s) successfully updated");
break;
case TransactionResult.AlreadyDispatched;
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
break;
case TransactionResult.RecordNotRecorded;
DisplayError("Record has not yet been recorded");
break;
case TransactionResult.AlreadyRemoved:
DisplayError("This invoice number was remove from dispatch sheet before!!");
break;
}
}
These methods in turn call a variety of helper methods, each of which does one thing and one thing only. This could be referred to as separation of concerns, which is really important for structured code.
Here's the rest of the methods:
enum TransactionResult
{
Success,
AlreadyDispatched,
RecordNotRecorded,
AlreadyRemoved
}
private bool ExecuteSelectStatus(SqlConnection connection, SqlTransaction transaction, string invoiceNum, string custPONum)
{
using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#invoiceNum", invoiceNum);
command.Parameters.AddWithValue("#custPONum", custPONum);
using (var myReader = command.ExecuteReader())
{
if (myReader.Read())
{
string invoice1 = (myReader["status"].ToString());
if (invoice1 == "0")
{
return false;
}
}
}
return true;
}
}
private int ExecuteRemoveInvoice(SqlConnection objConnection, SqlTransaction transaction, string loadSheetNum, string invoiceNum, string removeUser)
{
try
{
using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#loadSheetNum", loadSheetNum);
cmd.Parameters.AddWithValue("#invoiceNum", invoiceNum);
cmd.Parameters.AddWithValue("#removeUser", removeUser);
return cmd.ExecuteNonQuery();
}
}
catch (SqlException ex)
{
if (ex.Number == 2627) //Primary key violation
{
return -1;
}
}
}
protected TransactionResult ExecuteInvoiceTransaction(string invoiceNum, string custPONum, string loadSheetNum, string removeUser)
{
var strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();
using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
{
objConnection.Open();
using (SqlTransaction transaction = objConnection.BeginTransaction())
{
var ok = ExecuteSelectStatus(objConnection, transaction, invoiceNum, custPONum);
if (!ok) return TransactionResult.AlreadyDispatched;
var a = ExecuteRemoveInvoice(objConnection, transaction, loadSheetNum, invoiceNum, removeUser);
switch a
{
case -1:
return TransactionResult.AlreadyRemoved;
case 0:
return TransactionResult.RecordNotRecorded;
default:
transaction.Commit();
return TransactionResult.Success;
}
}
}
}
public void DisplayTotals(int i)
{
////Read invoice qty from grid view 2
string invoice = GridView2.Rows[i].Cells[5].Text;
decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
txtInvoiceTotal.Text = invoiceTotal.ToString();
////Read invoice weight from grid view 2
string weight = GridView2.Rows[i].Cells[6].Text();
decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
txtQtyWeight.Text = invoiceWeight.ToString();
}
public void DisplaySuccess(string message)
{
lblError.ForeColor = Color.Green;
lblError.Text = message;
}
public void DisplayError(string message)
{
lblError.ForeColor = Color.Red;
lblError.Text = message;
}
A few things to note:
You don't need to call Dispose() if you are using using.
You should always catch the most specific exception possible, per Microsoft's guidance. My example does this.
The exception handling for the primary key error is isolated into the method that calls the stored procedure. The overall business logic shouldn't have to know details about the SQL implementation. I've shown how you can identify the specific error based on this post.
Because there are four possible outcomes, I added an enumeration called TransactionResult so we could return the status to the caller easily.
Some of these methods are short-- just two lines-- and that is OK. The main reason to separate them out is to give them a meaningful name and make the code shorter and easier to read.
This code is much more structured but it could still be improved! In many implementations, the code that accesses the database is actually moved to a completely different layer or project.
See if this works. Moved your if/else together:
protected void Button2_Click(object sender, EventArgs e)
{
try
{
for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
{
var row = GridView2.Rows[i];
CheckBox chk = row.FindControl("chkInvoice") as CheckBox;
if (chk != null && chk.Checked)
{
string strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();
using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
{
objConnection.Open();
using (SqlTransaction transaction = objConnection.BeginTransaction())
{
string SID = GridView2.Rows[i].Cells[3].Text.Trim();
SqlDataReader myReader = null;
using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#invoiceNum", SID);
command.Parameters.AddWithValue("#custPONum", GridView2.Rows[i].Cells[4].Text.Trim());
myReader = command.ExecuteReader();
if (myReader.Read())
{
string invoice1 = (myReader["status"].ToString());
if (invoice1 == "0")
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
}
else if (invoice1 == "1")
{
using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#loadSheetNum", txtDispatchNum.Text);
cmd.Parameters.AddWithValue("#invoiceNum", SID);
cmd.Parameters.AddWithValue("#removeUser", lblUsername.Text.Replace("Welcome", ""));
int a = cmd.ExecuteNonQuery();
cmd.Dispose();
if (a > 0)
{
dt.Rows.RemoveAt(i);
////Read invoice qty from grid view 2
string invoice = GridView2.Rows[i].Cells[5].Text.ToString();
decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
txtInvoiceTotal.Text = invoiceTotal.ToString();
////Read invoice weight from grid view 2
string weight = GridView2.Rows[i].Cells[6].Text.ToString();
decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
txtQtyWeight.Text = invoiceWeight.ToString();
lblError.ForeColor = Color.Green;
lblError.Text = "Selected record(s) successfully updated";
}
else
{
lblError.ForeColor = Color.Red;
lblError.Text = " Record has not yet been recorded";
}
}
//objConnection.Close();
transaction.Commit();
}
}
}
GridView2.DataSource = dt;
GridView2.DataBind();
txtInvoiceCount.Text = dt.Rows.Count.ToString();
}
}
}
}
}
catch (Exception ex)
{
if (ex.Message.StartsWith("Violation of PRIMARY KEY constraint"))
{
lblError.ForeColor = Color.Red;
lblError.Text = " This invoice number was remove from dispatch sheet before!!";
}
else
{
// re-throw the error if you haven't handled it
lblError.Text = ex.Message;
throw;
}
}
}
}
I use Dapper to select data form Mssql, It result display "null"
(use stored procedureć List to get data, and "myDictionary[0].Account" and myDictionary[0].Password to get detail information) ,
but MS SQL database have data.
How can I fix code ? thanks.
public void Do_Click(object sender, EventArgs e)
{
string strAccount = Request.Form["userAccount"];
string strPassword = Request.Form["userPwd"];
using (var conn = new SqlConnection(strConn))
{
try
{
conn.Open();
List<LoginModel> myDictionary =
conn.Query<LoginModel>(#"uspSelectLoginChk",
new { LoginAcc = strAccount, LoginPsd = strPassword }, commandType: CommandType.StoredProcedure).ToList();
string strAccountChk = myDictionary[0].Account;
string strPASChk = myDictionary[0].Password;
conn.Close();
if (strAccountChk != null && strAccountChk != null)
{
Response.Redirect("test.aspx");
}
else
{
}
}
catch (Exception ex)
{
response.write( ex.ToString());
}
}
}
Try this one,
// Modified your code
public void Do_Click(object sender, EventArgs e)
{
string strAccount = Request.Form["userAccount"];
string strPassword = Request.Form["userPwd"];
var _para = new DynamicParameters();
_para.Add("#LoginAcc", strAccount);
_para.Add("#LoginPsd", strPassword);
var _list = _con.Query<LoginModel>("uspSelectLoginChk", _para, commandType: CommandType.StoredProcedure); // _con is SqlConnection _con = new SqlConnection("your connection string")
if(_list != null) {
Response.Redirect("test.aspx");
}
}
you need to check:
execute sp in sql with parameter which can view in debug the code.
example:
exec uspSelectLoginChk 'LoginAccValue', 'LoginPsdValue'
if a any data in sql execute,your code is error,if no data, you can insert data before with a data debug result.
Thanks
private static final String DB_URL = "jdbc:derby://localhost:1527/ShopDB";
private static final String DB_CLOSE = DB_URL + ";shutdown=true";
private static final String DB_DRIVER = "org.apache.derby.jdbc.ClientDriver";
private static Connection con = null;
public WebshopDAO() {
try {
Class.forName(DB_DRIVER).newInstance();
con = DriverManager.getConnection(DB_CLOSE);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
I created a WebshopDAO object in another class. After that, I called a method in the WebDAO:
public CatalogDTO createCatalogDTO() {
String query = "SELECT * FROM Catalog";
CatalogDTO catalog = new CatalogDTO();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
Catalog c = new Catalog();
c.setCName(rs.getString("CName"));
c.setCategoryNr(rs.getInt("CategoryNr"));
c.setSupercategoryNr(rs.getInt("SupercategoryNr"));
catalog.addCatalog(c);
}
} catch (SQLException e) {
e.getMessage();
}
return catalog;
}
So when I call the createCatalogDTO method, I get a NullPointerException. I don't know why. I checked the driver url and the db url and they are correct. I am using servlets for the first time. The class that uses this WebshopDAO is a servlet and I have a bit of a problem using the debugger.
Can you guys tell me the possible mistakes? I am looking for hours but I just can't find it.
EDIT:
Here is what I get:
java.lang.NullPointerException
WebshopDAO.createCatalogDTO(WebshopDAO.java:96)
Navigation.doGet(Navigation.java:28)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I am working on a web application using jsp and servlet using oracle.jdbc.OracleDriver.This code,working fine on my PC,but when trying to deploy build of application on other server,i am getting Exception like this.
java.sql.SQLException: Missing defines
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:158)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:305)
at oracle.jdbc.driver.OracleStatement.prepareAccessors(OracleStatement.java:793)
at oracle.jdbc.driver.T4CResultSetAccessor.getCursor(T4CResultSetAccessor.java:235)
at oracle.jdbc.driver.ResultSetAccessor.getObject(ResultSetAccessor.java:95)
at oracle.jdbc.driver.OracleCallableStatement.getObject(OracleCallableStatement.java:1947)
at org.apache.tomcat.dbcp.dbcp.DelegatingCallableStatement.getObject(DelegatingCallableStatement.java:143)
at cwep.Login.processRequest(Login.java:127)
at cwep.Login.doPost(Login.java:198)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:852)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:584)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1508)
at java.lang.Thread.run(Unknown Source)
After debugging my application,i found that when I am calling database(Oracle 10g) procedure on server side and getting cursor using callableStatement.registerOutParameter(1,OracleTypes.CURSOR), I am getting above Exception at
callableStatement.execute(); statement.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
static String CNPOOL = "cnpool";//Getting CNPOOL correctly for database connection
CallableStatement cs = null;
static DataSource dataSource;//Declared as global
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
CallableStatement cs = null;
String str = conectionPool;
System.out.println(str);
try {
InitialContext initContext = new InitialContext();
Context context = (Context) initContext.lookup("java:/comp/env");
dataSource = (DataSource) context.lookup(str);
System.out.println(" CxN Pool " + str);
String username = request.getParameter("username");
String password = request.getParameter("password");
ecode = Integer.parseInt(username);
System.out.println(" eCode " + ecode);
try {
con = ConnectionBean.getConnection(dataSource);
System.out.println(" CxN " + con.toString());
} catch (Exception e) {
System.out.println(" Opening the Cxn 1st Time" + e);
}
if(con!=null)
{
System.out.println(" Before Calling proc_user_login " + ecode);
cs = con.prepareCall("{call proc_user_login(?,?,?,?,?)}");
cs.setInt(1, empcode);
cs.setString(2, password);
cs.registerOutParameter(3, Types.NUMERIC);
cs.registerOutParameter(4, Types.NUMERIC);
cs.registerOutParameter(5, Types.VARCHAR);
try {
cs.execute();
} catch (Exception e) {
System.out.println("--------------------After executing first proc----------------------- ");
}
int message = cs.getInt(3);
if (message == 0) {
cs = con.prepareCall("{call proc_get_XXXlist(?,?)}");
cs.setInt(1, empcode);
cs.registerOutParameter(2, OracleTypes.CURSOR);
try {
System.out.println("Before executing XXXList proc ");
cs.execute(); //GETTING EXCEPTION AT THIS STATEMENT
System.out.println("After executing XXXList");
} catch (Exception e) {
System.out.println("exception in After executing secod proc ");
}
ResultSet rset = (ResultSet) cs.getObject(2);
Vector v1 = new Vector();
Vector v2 = new Vector();
Vector v3 = new Vector();
while (rset.next()) {
v1.addElement(rset.getString(1));
v2.addElement(rset.getString(2));
v3.addElement(rset.getString(3));
}
//rset.last();
String[] str1 = new String[v1.size()];
String[] str2 = new String[v2.size()];
String[] str3 = new String[v3.size()];
v1.copyInto(str1);
v2.copyInto(str2);
v3.copyInto(str3);
request.setAttribute("ecode", Integer.toString(ecode));
request.setAttribute("clientid", str1);
request.setAttribute("constring", str2);
request.setAttribute("URL", str3);
RequestDispatcher rd = request.getRequestDispatcher("XXX.jsp");
rd.forward(request, response);
//response.sendRedirect("XXX.jsp");
} else {
response.sendRedirect("index.jsp?val=" + message);
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("EEE---" + e);
Utility.log("FinalExceptionToServlet.namelookup:", e.toString(), "SERVER", "E");
}
}
In this code,First database login_usr procedure execute properly,but when trying to execute 2nd procedure,which returns a cursor as outparameter,i'm getting above exception.If same code working fine on my PC,then why it throws exception when trying to execute callablestatement after Serverside deployment.Here I'm using Ojdbc14.jar and classes12.jar.Is there is any .jar missmatch..???
Thanks in advance.
As you have mentioned that the code was running earlier, Here the culprit could be OracleTypes. As its abstract class you need correct and concrete implementation of it which is your Driver.
Verify the version of the JDBC driver and the type of JDBC driver (Thin or OCI) you
Download new jar from oracle site or from here.
Also, try using oracle.jdbc.OracleTypes before looking for drivers.
e.g. cn.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR);
I have an access database with 3 tables.
People
Gifts
PeopleGifts
Using VS 2008, what is the quickest way to get a page up and running which allows me to run queries against these tables and do basic inserts.
I want to have comboboxs bound to fields in the table so a user can click on a person and click on a gift and they click "Add".
The quickest way? Iron Speed
try using an oleDBDataAdapter and a formview
public interface IOleDbDataGateway
{
void ExecuteNonQuery(string sql, params object[] args);
object ExecuteScalar(string sql, params object[] args);
DataTable FillDataTable(string sql, params object[] args);
}
public class OleDbDataGateway : IOleDbDataGateway
{
private readonly string connectionString;
public OleDbDataGateway(string connectionString)
{
this.connectionString = connectionString;
}
public void ExecuteNonQuery(string sql, params object[] args)
{
if (args != null)
{
sql = string.Format(sql, args);
}
var connection = new OleDbConnection(connectionString);
var command = new OleDbCommand(sql, connection);
connection.Open();
try
{
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
}
public object ExecuteScalar(string sql, params object[] args)
{
if (args != null)
{
sql = string.Format(sql, args);
}
var connection = new OleDbConnection(connectionString);
var command = new OleDbCommand(sql, connection);
connection.Open();
try
{
return command.ExecuteScalar();
}
finally
{
connection.Close();
}
}
public DataTable FillDataTable(string sql, params object[] args)
{
if (args != null)
{
sql = string.Format(sql, args);
}
var connection = new OleDbConnection(connectionString);
var adapter = new OleDbDataAdapter(sql, connection);
var table = new DataTable();
connection.Open();
try
{
adapter.Fill(table);
}
finally
{
connection.Close();
}
return table;
}
}