updating a row gives error Operation must use an updateable query - asp.net

I'm getting this error when I'm trying to update a record:
ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]
Operation must use an updateable query
However when I add a new record, it would add just fine.
I did some searching and found out that the problem is because The ASP.NET worker process does not have permission to update the database. But how am I being able to insert a new record (Isn't inserting updating the database!) but not update (set a record to a different value).
OdbcConnection DbConnection = new OdbcConnection("DSN=inv");
DbConnection.Open();
try
{
string newPassword = password1.Text;
OdbcCommand DbCommand = new OdbcCommand("UPDATE Users" + " SET [Password] = '" + newPassword + "'" + " Where Name = '" + Session["LoginId"] + "'" + ";", DbConnection);
DbCommand.ExecuteNonQuery();
Server.Transfer("Default.aspx", true);
}

You will often get that error if you don't have a primary key declared on that table.
Your code is also pretty ugly, at the very least you should be using a parameterized query:
OdbcCommand DbCommand = new OdbcCommand("UPDATE Users SET [Password] = #Password Where Name = #Name", DbConnection);
var param = DbCommand.Parameters.Add("#Password", OdbcType.Text);
param.Value = passWord;
param = DbCommand.Parameters.Add("#Name", OdbcType.Text);
param.Value = Session["LoginId"];
And I hope this isn't anything more than a toy/demo app -- storing passwords in the clear is bad. Storing passwords in access in the clear is a double bad.

Related

Can't Update Database from ASP.NET Webform

I can't get an ASP.NET webform to update a database. I'm trying to edit an existing record in the database. The webform populates the data from the record into the form. The user then changes data and updates the record in the database when the form is submitted.
The problem is that nothing is changed in the database when a modified form is submitted. What am I doing wrong here? The SQL works in MSSQL Management Studio.
Thanks.
private void SaveToDatabase ()
{
using (SqlConnection conn = new SqlConnection (_connectionString_Bluebook))
{
conn.Open ();
string sql = #"update Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=" + _accountNo;
using (SqlCommand command = new SqlCommand (sql, conn))
{
command.Parameters.Add (new SqlParameter ("#CompanyName", TextBox_CompanyName.Text));
command.Parameters.Add (new SqlParameter ("#AccountNo", TextBox_Account.Text));
command.ExecuteNonQuery ();
}
conn.Close ();
}
}
Try adding a parameter for the original account number to your query. The example below uses strongly-typed parameters for security and performance, taking a guess at your actual SQL data types and column lengths, which you should change to your actual definitions.
private void SaveToDatabase()
{
using (SqlConnection conn = new SqlConnection(_connectionString_Bluebook))
{
conn.Open();
string sql = #"update dbo.Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=#OriginalAccountNo;
IF ##ROWCOUNT = 0 RAISERROR('Account number %s not found',16,1,#OriginalAccountNo)";
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add(new SqlParameter("#CompanyName",SqlDbType.VarChar,100).Value = TextBox_CompanyName.Text;
command.Parameters.Add(new SqlParameter("#AccountNo", SqlDbType.Char, 10).Value = TextBox_Account.Text;
command.Parameters.Add(new SqlParameter("#OriginalAccountNo", SqlDbType.Char, 10).Value = _accountNo;
command.ExecuteNonQuery();
}
}
}
If the row is still not updated as expected, make sure _accountNo contains the proper value.
EDIT:
I added a RAISERROR statement to the SQL batch to facilitate this, which you could leave in the code if the not found condition should never occur.
If the SQL Params are not working, then try this way:
comm = new SqlCommand("update student_detail set s_name= '" + txtname.Text + "', age= "+txtage.Text+" , course=' " + txtcourse.Text + "' where roll_no = " + txtrn.Text + " ", conn);
Try to place the debugger and provide the exact error of the compiler

insert query in MySQL error

I have create a function. When the user click the button, data will automatic inset into order table. But it keep give me error. I use the way to do my register page is working fine.
Error Message:
An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order(UserId, OrderStatus, OrderDate) values ('kit', 'Pending', '2014-12-08 22:4' at line 1
If Session("OrderId") Is Nothing Then
Dim conn As New MySqlConnection
conn.ConnectionString = "server = localhost; user id = root; password = root; database = db_fyp"
Dim com As New MySqlCommand
conn.Open()
Dim query As String
query = "insert into order(UserId, OrderStatus, OrderDate) values (#UserId, #OrderStatus, #OrderDate)"
com = New MySqlCommand(query, conn)
com.Parameters.AddWithValue("#UserId", Session("Username"))
com.Parameters.AddWithValue("#OrderStatus", "Pending")
com.Parameters.AddWithValue("#OrderDate", Now())
com.ExecuteNonQuery()
conn.Close()
End If
Return Nothing
End Function
Order is a reserved keyword in any SQL language known. I really suggest to change that table name to something less problematic. In the meantime you could change the query to
query = "insert into `order` (UserId, OrderStatus, OrderDate) " & _
"values (#UserId, #OrderStatus, #OrderDate)"

direct SQL execution to get count using Enterprise library

I am new to asp.net development and using enterprise library in my application in the following way.
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetStoredProcCommand("sp_MakePayment");
db.AddInParameter(cmd, "#BillGenID", System.Data.DbType.Int32);
db.SetParameterValue(cmd, "#BillGenID", billgenID);
db.AddInParameter(cmd, "#PayDate", System.Data.DbType.String, 50);
db.SetParameterValue(cmd, "#PayDate", mypaydate.Text);
db.AddInParameter(cmd, "#TransNo", System.Data.DbType.String, 50);
db.SetParameterValue(cmd, "#TransNo", transno.Text);
db.AddInParameter(cmd, "#AmtToPay", System.Data.DbType.Double);
db.SetParameterValue(cmd, "#AmtToPay", Convert.ToDouble(paidamount.Text));
////Execute Stored Procedure
int i = 0;
i = db.ExecuteNonQuery(cmd);
Now I am in a situation where i need to run this inlnie query using the same method to get the count of records and read in a variable. for example following query to find existing bill.
string bill_id = "1234";
string dofpayment = "11/03/2011";
mysql = "Select count(*) from payments where bill_id = " + bill_id + " and payment_date = " + dofpayment ;
Now how to incorporate the above lines using the enterprise library block.
thanks
If you enterprise library supports text commands alongside with stored procedures, then you should write a code which creates a text command and then passes your bill_id and dofpayment as parameters to it.
Otherwise, you need to create a stored procedure with these two parameters and then call that in similar way shown in your code example for stored procedure.
I hope this helps!
string sSql = "SELECT CustomerID, CompanyName, City, Country" + " FROM Customers WHERE Country = #sCountry"; Database db = DatabaseFactory.CreateDatabase(); DBCommandWrapper cmd = db.GetSqlStringCommandWrapper(sSql); cmd.AddInParameter("#sCountry", DbType.String, sCountry); DataSet ds = new DataSet(); db.LoadDataSet(cmd, ds, "Customers");
please read the msdn reference

MySQL / ASP.NET Stored Procedures

Hopefully this is not a ServerFault question...
I'm working forward on migrating a project from storing data in XML Serialization to a MySQL database. I'm using the example provided me from a previous question answered yesterday.
Connecting using phpMyAdmin and MySQL Workbench I've created a Stored Procedure called 'sprocOrderSelectSingleItem'. It seems to work well with MySQL for all I can tell. When I run the SHOW CREATE PROCEDURE sprocOrderSelectSingleItem it returns the following:
CREATE DEFINER=username#% PROCEDURE sprocOrderSelectSingleItem(IN orderID INTEGER)
BEGIN SELECT * FROM tblOrders WHERE ID=orderID; END
My cooperative ASP.NET code goes something like this:
public static Order GetItem(int ID)
{
Order objOrder = null;
using (OdbcConnection objConnection = new OdbcConnection(Utils.ApplicationConfiguration.ConnectionString))
{
OdbcCommand objCommand = new OdbcCommand("sprocOrderSelectSingleItem", objConnection);
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.Parameters.AddWithValue("orderID", ID);
objConnection.Open();
using (OdbcDataReader objReader = objCommand.ExecuteReader())
{
if (objReader.Read())
{
objOrder = FillDataRecord(objReader);
}
objReader.Close();
}
objConnection.Close();
}
return objOrder;
}
When I view the page I get the following error message:
ERROR [42000] [MySQL][ODBC 5.1 Driver][mysqld-5.0.77]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'sprocOrderSelectSingleItem' at line 1
Really not catching on to what could be missing or going wrong. Are there any additional tests I should/could be running to confirm things are working on the MySQL side? Am I missing a step to pass the Stored Procedure call correctly in ASP.NET? The code breaks at the line of:
using (OdbcDataReader objReader = objCommand.ExecuteReader())
Replacing the line of
OdbcCommand objCommand = new OdbcCommand("sprocOrderSelectSingleItem", objConnection);
with this instead
OdbcCommand objCommand = new OdbcCommand("SELECT * FROM tblOrders WHERE ID=" + ID + ";", objConnection);
and everything works as expected.
Thanks for any help you guys can provide.
Your can run an execute on sprocOrderSelectSingleItem in Mysql directly with the ID parameter.
It will show that your StoredProc run correctly.
Here is a sample code in C# that call a stored proc.
OdbcCommand salesCMD = new OdbcCommand("{ CALL SalesByCategory(?) }", nwindConn);
salesCMD.CommandType = CommandType.StoredProcedure;
OdbcParameter myParm = salesCMD.Parameters.Add("#CategoryName", OdbcType.VarChar, 15);
myParm.Value = "Beverages";
OdbcDataReader myReader = salesCMD.ExecuteReader();
Look at the "Call" in the OdbcCommand and the "?" for the parameter that is later supplied with a value.
Can you try something like below:
OdbcCommand cmd = new OdbcCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "{call LoadCustCliOrders(?,?,?,?)}";
cmd.Parameters.Add("CUST_ID",OdbcType.Int);
cmd.Parameters.Add("CLIENT_ID",OdbcType.Int);
cmd.Parameters.Add("DATE_FROM",OdbcType.Date);
cmd.Parameters.Add("DATE_TO",OdbcType.Date);
...
cmd.Parameters["CUST_ID"].Value = _CustId;
cmd.Parameters["CLIENT_ID"].Value = _ClientId;
cmd.Parameters["DATE_FROM"].Value = _DateFrom;
cmd.Parameters["DATE_TO"].Value = _DateTo;
cmd.ExecuteReader
Are you sure that you are using the same username or user with the same access privileges.
I think you need to add the word "CALL" before the stored proc.
It should be CALL sprocOrderSelectSingleItem and try.

Issue with ODBC.Net connection to MySQL DB

I'm thinking the problem here is with my SQL Syntax, but I'm not sure and need a fresh pair of eyes to check it out. This is the code I'm using to connect to and then insert into the DB:
OdbcConnection datConn = CreateDataConn();
datConn.Open();
OdbcCommand comm = new OdbcCommand();
comm.CommandText = "INSERT INTO userdata (key, secretkey, uid) VALUES ('" + token + "', '" + secret + "', '" + twitterid + "');";
comm.Connection = datConn;
comm.ExecuteNonQuery();
datConn.Close();
And here is the CreatDataConn() method:
private OdbcConnection CreateDataConn()
{
OdbcConnection dbConn = new OdbcConnection();
dbConn.ConnectionString = "Dsn=MySQL;database=twittertest;option=0;port=0;server=localhost;uid=root;pass=Red!4jedi";
return dbConn;
}
I created a DSN to the database, which is hosted on my machine.
When I run the application I get this error:
ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.1.51-community]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key, secretkey, uid) VALUES ('127090765-i3aZl71LPSVUCPZs9kHSYeBli0vWpbq0BaM1roYC' at line 1
But for the life of me I can't figure out what's wrong with my syntax...It's prolly something simple, but again, I need a pair of fresh eyes to look at this.
key is a probably a reserved word. in MySQL, you can get around this by adding backticks (`) around a column name (so '`key`'instead of 'key'), but you should try not to have reserved words as entity names.

Resources