Update Query problem in asp.net c# and Mysql using odbc - c#

when i specify values in my update query the query works fine and the database gets updated, but when i use parameters in my query the database does not update
here is the code i have written
try
{
OdbcConnection MyConnection = new OdbcConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString);
MyConnection.Open();
String MyString = "UPDATE orddetpabak SET jud1=#jud1,jud2=#jud2,jud3=#jud3,adv=#adv where fil_no=#fil_no AND orderdate=#orderdate";
OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
String j1=DropDownList4.SelectedValue;
String j2=DropDownList5.SelectedValue;
String j3=DropDownList6.SelectedValue;
String j4=TextBox4.Text;
String j5 = HiddenField1.Value;
String j6 = TextBox3.Text;
MyCmd.Parameters.AddWithValue("#jud1",j1);
MyCmd.Parameters.AddWithValue("#jud2",j2);
MyCmd.Parameters.AddWithValue("#jud3",j3);
MyCmd.Parameters.AddWithValue("#adv",j4);
MyCmd.Parameters.AddWithValue("#fil_no",j5);
MyCmd.Parameters.AddWithValue("#orderdate",j6);
Response.Write(DropDownList4.SelectedValue);
Response.Write(" " + DropDownList5.SelectedValue);
Response.Write(" " + DropDownList6.SelectedValue);
Response.Write(" " + TextBox4.Text);
Response.Write(" " + HiddenField1.Value);
Response.Write(" " + TextBox3.Text);
MyCmd.ExecuteNonQuery();
//MyConnection.Close();
}
catch(Exception epp)
{
Response.Write(epp);
}
Please Help

As far as I know you cannot use named parameters in MySQL. If you change your string to be
String MyString = "UPDATE orddetpabak SET jud1=?,jud2=?,jud3=?,adv=?
where fil_no=? AND orderdate=?";
and your parameters as:
MyCmd.Parameters.AddWithValue("",j1);
MyCmd.Parameters.AddWithValue("",j2);
MyCmd.Parameters.AddWithValue("",j3);
MyCmd.Parameters.AddWithValue("",j4);
MyCmd.Parameters.AddWithValue("",j5);
MyCmd.Parameters.AddWithValue("",j6);
Hope this helps.

It can be like the following: (I'm using the ADO.NET driver for MySQL version 6.3.7.0, latest one had some issues).
public bool UpdateCustomerIAR(IAR oIAR)
{
bool bRetVal = false;
try
{
MySqlConnection dbConnection = new MySqlConnection(APPSConn.ConnectionString);
MySqlCommand dbCommand = dbConnection.CreateCommand();
string szSQL = string.Empty;
szSQL = "UPDATE schema.table_name SET field_name_one=?field_name_one";
szSQL += " WHERE field_name_two=?field_name_two";
using (MySql.Data.MySqlClient.MySqlConnection conn = new
MySql.Data.MySqlClient.MySqlConnection(APPSConn.ConnectionString))
{
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = szSQL;
cmd.Parameters.AddWithValue("?field_name_one", oIAR.Title);
cmd.Parameters.AddWithValue("?field_name_two", oIAR.IARID.ToString());
conn.Open();
cmd.ExecuteNonQuery();
bRetVal = true;
}
return bRetVal;
}
catch (MySqlException ex)
{
ErrorHandler(ex.ToString());
return bRetVal;
}
catch (Exception ex)
{
ErrorHandler(ex.ToString());
return bRetVal;
}
}

Related

C# Excel VSTO OLE DB Parameters Error must declare scalar variable

In Excel writing a VSTO Plugin (using C#) I'm trying to retrieve a value from a SQL database using OLEDB. When I debug this function, it fails on the catch.
The message I get is:
must declare the scalar variable \"#uname\"
But I already did this when I bound the parameter. What am I doing wrong?
public static int getUserID(string username)
{
int result = 0;
string sql = #"select top 1 [ID] FROM " + tbl_users + " WHERE ( [UNAME]=#uname );";
Console.WriteLine("sql: " + sql);
using (OleDbConnection conn = new OleDbConnection(connStr))
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#uname", username);
result = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
result = -15;
}
finally
{
conn.Close();
conn.Dispose();
}
}
return result;
}
So I think I figured it out... This change works, but I don't really like it.
First I need to use OleDb parameter binding and not SqlParameter binding.
It also seems like OleDb does not like custom naming parameters like #uname and instead relies on the order of parameters (I don't like this).
So here's the fix in case anyone was interested:
public static int getUserID(string username)
{
int result = 0;
string sql = #"select top 1 [ID] FROM " + tbl_users + " WHERE ( [UNAME]=? );";
Console.WriteLine("sql: " + sql);
using (OleDbConnection conn = new OleDbConnection(connStr))
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = Convert.ToString(username);
result = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
result = -15;
}
finally
{
conn.Close();
conn.Dispose();
}
}
return result;
}

c# Invalid attempt to read when no data is present

I am unable to find the problem here but this does not work! Any help will be appreciated.
It is a bool thing BTW.Every time i debug, it logs an error as follows
Invalid attempt to read when no data is present
ICCqueueLabelDropDownList.Items.Clear();
string queryString = "(SELECT [name] FROM [asterisk].[dbo].[sip_friends] where name = '" + phoneNumberDropDownList.SelectedItem + "');";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand selectCmd = new SqlCommand(queryString, conn);
SqlDataReader myReader = null;
bool value = false;
try
{
conn.Open();
myReader = selectCmd.ExecuteReader();
//myReader.Read();
if (myReader["name"].ToString() != "" ) /* ( myReader["name"].ToString() != "" */
{
myReader.Read();
value = true;
}
}
catch (Exception ex)
{
//ErrorLabel.Text = ex.Message;
hiba.Visible = true;
hiba.Text = ex.Message + "\n Check Insert Call User Device ÁLERT!";
}
myReader.Close();
conn.Close();
return (value);
}
#andrew, kindly go through below code and let me know is it working for you or not?
string connectionString = "[YOUR_CONNECTION_STRING]";
ICCqueueLabelDropDownList.Items.Clear();
string queryString = "(SELECT [name] FROM [asterisk].[dbo].[sip_friends] where name = '" + phoneNumberDropDownList.SelectedItem + "');";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand selectCmd = new SqlCommand(queryString, conn);
SqlDataReader myReader = null;
bool value = false;
try
{
conn.Open();
myReader = selectCmd.ExecuteReader();
if (myReader.Read())
{
if (myReader["name"].ToString() != "")
{
value = true;
}
}
}
catch (Exception ex)
{
}
myReader.Close();
conn.Close();
return (value);
}

Generic C# Function That Return Value From Database

The following function get parameters and return first value from sql server table. Its generic and very easy to use to get one value but it has security vulnerability of SQL Injection. May anyone help to alter the code to make it a parametric or any other way to secure for SQL Injection?
public static string getFieldValue(string tableName, string returnField, string whereCondition)
{
SqlConnection con = new SqlConnection(Utilities.ConnectionString());
SqlDataReader reader;
string returnValue;
try
{
string sql;
if (whereCondition != "")
sql = "SELECT " + returnField + " as ReturnField FROM " + tableName + " WHERE " + whereCondition;
else
sql = "SELECT " + returnField + " as ReturnField FROM " + tableName;
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
reader = cmd.ExecuteReader();
if (reader.Read())
{
returnValue = reader["ReturnField"].ToString();
reader.Close();
return returnValue;
}
else
{
reader.Close();
return "";
}
}
catch (Exception err)
{
throw new ApplicationException(err.Message);
}
finally
{
con.Close();
con.Dispose();
}
}

How do I delete a row from a Microsoft Access table using c#

I've tried this code:
string sql = " DELETE FROM HotelCustomers WHERE [Room Number] =" + textBox1.Text;
OleDbConnection My_Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= c:\\Users\\Documents\\HotelCustomersOld.mdb");
My_Connection.Open();
OleDbCommand My_Command = new OleDbCommand(sql, My_Connection);
My_Command.ExecuteNonQuery();
Error: Data type mismatch in criteria expression, at the line:
My_Command.ExecuteNonQuery();
Use parametrized query to avoid all kind of errors
string sql = " DELETE FROM HotelCustomers WHERE [Room Number] =?";
using(OleDbConnection My_Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= c:\\Users\\Documents\\HotelCustomersOld.mdb"))
{
My_Connection.Open();
OleDbCommand My_Command = new OleDbCommand(sql, My_Connection);
My_Command.Parameters.Add("#p1", textBox1.Text);
My_Command.ExecuteNonQuery();
}
In your case the Room NUmber field is of Text type so, you need to enclose the value in single quotes, but this is really wrong. You expose your code to maliciuos text written by your user inside the text box. A very simple and funny example here
Which type is your [Room Number] column? If it is a string then you have to write the value with inverted comma or quotation mark (I'm not sure which of both is used in Access).
string sql = " DELETE FROM HotelCustomers WHERE [Room Number] = '" + textBox1.Text + "'";
To avoid SQL injektion you should use Parameters instead of the string operation.
public static void DeleteLine(string kv)
{
OleDbConnection myConnection = GetConnection();
string myQuery = "DELETE FROM Cloth WHERE [ClothName] = '" + kv + "'";
OleDbCommand myCommand = new OleDbCommand(myQuery, myConnection);
try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Exception in DBHandler", ex);
}
finally
{
myConnection.Close();
}
}
try
{
OleDbConnection con = new OleDbConnection("provider = microsoft.ace.oledb.12.0;data source = E:\\Sohkidatabase\\Sohki.accdb");
con.Open();
str = "select * from compny_info where id=" + comboBox1.Text.Trim() + "";
com = new OleDbCommand(str, con);
OleDbDataReader reader = com.ExecuteReader();
if (reader.Read())
{
textBox1.Text = reader["regis_no"].ToString();
textBox2.Text = reader["comp_oner"].ToString();
textBox3.Text = reader["comp_name"].ToString();
textBox4.Text = reader["comp_add"].ToString();
textBox5.Text = reader["tin_no"].ToString();
textBox6.Text = reader["email"].ToString();
}
con.Close();
reader.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
public static void DeleteLine(string kv) {
OleDbConnection myConnection = GetConnection();
string myQuery = "DELETE FROM Cloth WHERE [ClothName] = '" + kv + "'" ;
}

Generate database creation scripts

Is it possible to generate the database creation scripts for a SQL server database from .NET?
I am using C# and I would like to create some sort of an installer project for my application
on which I can select an existing database, generate the creation scripts and run them on another SQL server instance.
Yes, it is possible.
It's easy to do this with SMO, see Transfer class for scripting operations and Database class for database operations (create, drop, etc). Usage looks like this:
private StringCollection GetTransferScript(Database database)
{
var transfer = new Transfer(database);
transfer.CopyAllObjects = true;
transfer.CopyAllSynonyms = true;
transfer.CopyData = false;
// additional options
transfer.Options.WithDependencies = true;
transfer.Options.DriAll = true;
transfer.Options.Triggers = true;
transfer.Options.Indexes = true;
transfer.Options.SchemaQualifyForeignKeysReferences = true;
transfer.Options.ExtendedProperties = true;
transfer.Options.IncludeDatabaseRoleMemberships = true;
transfer.Options.Permissions = true;
transfer.PreserveDbo = true;
// generates script
return transfer.ScriptTransfer();
}
if you want to create database dynamically with c# code then here is the code:
you can do it like this also:
String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);
SqlConnection con = new SqlConnection();
con.ConnectionString = Connectionstring;
bool resultdbexistencx = CCMMUtility.CheckDatabaseExists(con, txt_DbName.Text);
if (!resultdbexistencx)
{
// if not exists create it check the user name for sub-admin avialibe or not.
if (txt_DbName.Text.Trim() == string.Empty) return;
string strDbCreate;
strDbCreate = "CREATE DATABASE " + txt_DbName.Text + " ON PRIMARY " +
"(NAME = " + txt_DbName.Text + "_Data, " +
"FILENAME = 'D:\\" + txt_DbName.Text + "Data.mdf', " +
"SIZE = 4MB, MAXSIZE = 10GB, FILEGROWTH = 100%) " +
"LOG ON (NAME = " + txt_DbName.Text + "_Log, " +
"FILENAME = 'D:\\" + txt_DbName.Text + ".ldf', " +
"SIZE = 4MB, " +
"MAXSIZE = 10GB, " +
"FILEGROWTH = 100%)";
SqlConnection sqlconn = new SqlConnection(Connectionstring);
SqlCommand cmd = new SqlCommand(strDbCreate, sqlconn);
try
{
sqlconn.Open();
sqlconn.ChangeDatabase("master");
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Int32 dbRollbackResult = RollBackTheWholetransaction(txt_DbName.Text.Trim(), Convert.ToInt32(HospitalResult));
if (dbRollbackResult == 1)
{
Response.Write(ex.Message);
lblMessage.DisplayMessage(StatusMessages.ErrorMessage, "There is some problem while generating the database or database name doesn't avialible.");
}
}
Here is the code of "RollBackTheWholetransaction" method :
private Int32 RollBackTheWholetransaction(String DbName, Int32 HospitalId)
{
Int32 result = 0;
try
{
String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);
SqlConnection con = new SqlConnection();
con.ConnectionString = Connectionstring;
String sqlCommandText = "ALTER DATABASE [" + DbName + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE";
String sqlCommandText1 = "DROP DATABASE [" + DbName + "]";
if (con.State == ConnectionState.Closed)
{
con.Open();
SqlConnection.ClearPool(con);
con.ChangeDatabase("master");
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
SqlCommand sqlCommand1 = new SqlCommand(sqlCommandText1, con);
sqlCommand1.ExecuteNonQuery();
ClsHospitals objHospiitals = new ClsHospitals();
String resultDbdelete = objHospiitals.DeleteHospital(HospitalId, Session["devSuperAdmin"].ToString());
if (resultDbdelete == "1")
{
result = 1;
}
else
{
result = 2;
}
}
else
{
SqlConnection.ClearPool(con);
con.ChangeDatabase("master");
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
SqlCommand sqlCommand1 = new SqlCommand(sqlCommandText1, con);
sqlCommand1.ExecuteNonQuery();
}
con.Close();
con.Dispose();
result = 1;
}
catch (Exception ex)
{
result = 0;
}
return result;
}
And here is the code to check existence of db in Database :
public static bool CheckDatabaseExists(SqlConnection tmpConn, string databaseName)
{
string sqlCreateDBQuery;
bool result = false;
try
{
// tmpConn = new SqlConnection("server=(local)\\SQLEXPRESS;Trusted_Connection=yes");
sqlCreateDBQuery = string.Format("SELECT database_id FROM sys.databases WHERE Name = '{0}'", databaseName);
using (tmpConn)
{
using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn))
{
if (tmpConn.State == System.Data.ConnectionState.Open)
{
tmpConn.Close();
tmpConn.Dispose();
}
tmpConn.Open();
tmpConn.ChangeDatabase("master");
int databaseID = (int)sqlCmd.ExecuteScalar();
tmpConn.Close();
result = (databaseID > 0);
}
}
}
catch (Exception ex)
{
result = false;
}
return result;
}
its the working code, hope it will work for you too....
You have to create your own installer by coding it all yourself. there are frameworks out there that make it much easyier.
like Windows Installer XML (WiX)
Windows installer
and more...
I would suggest you to have a look at WiX, worked with it and its quite easy and you can do much. Can be integrated in Visual Studio

Categories