c# - MySQL to Array to MSSQL Query Statement - c#

I'm working on a program to link two databases (MySQL and MSSQL) and show them in a datagrid table.
I'm getting a count to get the number of arrays value, then assigning the array, then using the array value to return into a datagrid table.
The problem I have is skuArray[RowCount++] = Convert.ToInt32(myReader[0]);is returning error: cannot convert int to string. I changed it to skuArray[RowCount++] = Convert.String(myReader[0]); and it complied correctly but gives the message Object reference not set to an instance of an object.
All SQL Queries have been tested and successfully execute.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
using System.Xml.Serialization;
using System.Data.SqlClient;
namespace SQL_Database_Connector
{
public partial class Sync_Databases : Form
{
string serverInfo; // MySQL Database Information
string portInfo;
string databaseInfo;
string usernameInfo;
string passwordInfo;
string MSserverInfo; // MSSQL Database Information
string MSdatabaseInfo;
string MSusernameInfo;
string MSpasswordInfo;
public string[] skuArray;
public string queryString;
public int RowCount;
public Sync_Databases()
{
InitializeComponent();
}
private void Sync_Databases_Load(object sender, EventArgs e)
{
if (File.Exists("data.xml")) // MySQL Database
{
XmlSerializer xs = new XmlSerializer(typeof(Information));
FileStream read = new FileStream("data.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
Information info = (Information)xs.Deserialize(read);
serverInfo = info.server;
portInfo = info.port;
databaseInfo = info.database;
usernameInfo = info.username;
passwordInfo = info.password;
read.Close();
}
try
{
string MyConnection = String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};", serverInfo, portInfo, databaseInfo, usernameInfo, passwordInfo);
string Query = "SELECT COUNT(*) " +
"FROM catalog_product_entity " +
"INNER JOIN catalog_product_entity_int " +
"ON catalog_product_entity_int.entity_id = catalog_product_entity.entity_id " +
"WHERE catalog_product_entity.sku IS NOT NULL " +
"AND catalog_product_entity.sku <> 0 " +
"AND(catalog_product_entity_int.attribute_id = '84' AND catalog_product_entity_int.value = '1');";
MySqlConnection MyConn = new MySqlConnection(MyConnection);
MySqlCommand MyCommand = new MySqlCommand(Query, MyConn);
MyConn.Open();
MySqlDataReader myReader;
myReader = MyCommand.ExecuteReader();
try
{
while (myReader.Read())
{
RowCount = myReader.GetInt32(0); // Get Row Count
//MessageBox.Show(RowCount.ToString()); // Test Row Count
}
}
finally
{
myReader.Close();
MyConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Problem with Row Count: "+ ex.Message);
}
try
{
string MyConnection = String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};", serverInfo, portInfo, databaseInfo, usernameInfo, passwordInfo);
string Query = "SELECT catalog_product_entity.sku AS 'SKU' " +
"FROM catalog_product_entity " +
"INNER JOIN catalog_product_entity_int " +
"ON catalog_product_entity_int.entity_id = catalog_product_entity.entity_id " +
"WHERE catalog_product_entity.sku IS NOT NULL " +
"AND catalog_product_entity.sku <> 0 " +
"AND(catalog_product_entity_int.attribute_id = '84' AND catalog_product_entity_int.value = '1');";
MySqlConnection MyConn = new MySqlConnection(MyConnection);
MySqlCommand MyCommand = new MySqlCommand(Query, MyConn);
MyConn.Open();
MySqlDataReader myReader;
myReader = MyCommand.ExecuteReader();
try
{
while (myReader.Read())
{
skuArray[RowCount++] = Convert.ToString(myReader[0]); // Assigning Array Values
//MessageBox.Show(skuArray.ToString()); //T est
}
}
finally
{
myReader.Close();
MyConn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Problem with MySQL query to capture Array: "+ ex.Message);
}
if (File.Exists("data2.xml")) // MSSQL Database
{
XmlSerializer xs = new XmlSerializer(typeof(Information));
FileStream read = new FileStream("data2.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
Information info = (Information)xs.Deserialize(read);
MSserverInfo = info.server;
MSdatabaseInfo = info.database;
MSusernameInfo = info.username;
MSpasswordInfo = info.password;
read.Close();
}
try
{
string connectionString = string.Format("Data Source={0}; Initial Catalog={1}; User ID={2}; Password={3};", MSserverInfo, MSdatabaseInfo, MSusernameInfo, MSpasswordInfo);
string sql = string.Format("SELECT ItemLookupCode,Description, Quantity, Price, LastReceived " +
"FROM Item " +
"WHERE ItemLookupCode IS IN {0} " +
"ORDER BY LastReceived ASC;", skuArray);
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "sql_table");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "sql_table";
SqlConnection conn = new SqlConnection();
}
catch (Exception ex)
{
MessageBox.Show("Problem with SQL query or connection: "+ ex.Message);
}
}
}
}

Where have you initialised the array?
I dont see any line which would say:
skuArray = new string[RowCount];
RowCount is just a placeholder i am using.

Related

C# WPF Mysql combobox duplicates values

I have a form that has 2 comboboxes. The first combobox (cb_CharacterName) which contains the character/user name and is loaded when the form opens, this works fine.
When a name is choosen in the cb_CharacterName the other combobox (Talent_Name) checks the (cb_CharacterName) combobox for the name and loads the talents the character/user has, this is also works fine.
However when a new character/user has been choosen in the cb_CharacterName the Talent_Name combobox does not remove the talents from the previous character, and just adds more to the list. At the same time if i select the same character twice i get duplicates.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MySql.Data.MySqlClient;
namespace Dark_Heresy
{
/// <summary>
/// Interaction logic for Character.xaml
/// </summary>
public partial class Character : Window
{
public Character()
{
InitializeComponent();
}
private void character_name_loader(object sender, RoutedEventArgs e)
{
string constring = "datasource= localhost; port=3306; username=root; password=MyPass;";
string Query = "SELECT Name_ FROM dark_heresy.character_";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
string charactername = myReader.GetString("Name_");
cb_CharacterName.Items.Add(charactername);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: \r\n" + ex);
}
}
private void cb_CharacterName_DropDownClosed(object sender, EventArgs e)
{
string constring = "datasource = localhost; port = 3306; username = root; password = MyPass;";
string Query = "SELECT * FROM dark_heresy.character_ WHERE Name_='" + cb_CharacterName.Text + "' ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string career = myReader.GetString("Class");
string world = myReader.GetString("World_Type");
string strength = myReader.GetInt32("Str").ToString();
string weaponskill = myReader.GetInt32("WS").ToString();
string ballisticskill = myReader.GetInt32("BS").ToString();
string fellowship = myReader.GetInt32("Fel").ToString();
string perception = myReader.GetInt32("Per").ToString();
string intelligence = myReader.GetInt32("Int_").ToString();
string agility = myReader.GetInt32("Agi").ToString();
string willpower = myReader.GetInt32("WP").ToString();
string toughness = myReader.GetInt32("Tough").ToString();
TextCareer.Text = career;
TextWorld.Text = world;
TextStrength.Text = strength;
TextWeaponskill.Text = weaponskill;
TextBallisticskill.Text = ballisticskill;
TextFellowship.Text = fellowship;
TextPerception.Text = perception;
TextIntelligence.Text = intelligence;
TextAgility.Text = agility;
TextWillpower.Text = willpower;
TextToughness.Text = toughness;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: \r\n" + ex);
}
}
private void cb_Talent_NameDropDownOpen(object sender, EventArgs e)
{
string constring = "datasource= localhost; port=3306; username=root; password=MyPass;";
string Query = "SELECT Talent_Name FROM dark_heresy.learned_talents WHERE Character_Name='" + cb_CharacterName.Text + "' ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDatabase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
string talent_name = myReader.GetString("Talent_Name");
Talent_Name.Items.Add(talent_name);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: \r\n" + ex);
}
}
private void cb_Talent_Name_DropDownClosed(object sender, EventArgs e)
{
string constring = "datasource = localhost; port = 3306; username = root; password = MyPass;";
string Query = "SElECT learned_talents.Talent_Name , talents.Description FROM dark_heresy.learned_talents, dark_heresy.talents WHERE learned_talents.Talent_Name = talents.TalentName AND learned_talents.Character_Name = '" + cb_CharacterName.Text + "';";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string talents_description = myReader.GetString("Description");
Talents_Description.Text = talents_description;
}
}
catch (Exception ex)
{
MessageBox.Show("Error: \r\n" + ex);
}
}
}
}
How can i make the Talent_Name combobox each time a new character/user or the samme has been choosen to flush the old informations and add the new ones in? i presume this would also remove the duplications problem.
Also, does WPF have a SelectedIndex? right now i am using DropdownClosed which is not the perfect choice, since when i use the arrows in the keyboard the values the character/user contains does not gets updated.
You want to call the Clear() method:
try
{
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
// You're missing this line!
Talent_Name.Items.Clear();
while (myReader.Read())
{
string talent_name = myReader.GetString("Talent_Name");
Talent_Name.Items.Add(talent_name);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: \r\n" + ex);
}
There should be a SelectedItem property you can use too grab the current item.

How to store Arabic language values from web-service in database

I'm trying to store some Arabic values I got from a web service, but when I select them from the database and show them in a DataGridView it just shows "?????". The three columns in the database are nvarchar(50). How should I be storing them?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
string user = "gamal";
string p1 = "GAM123";
string p2 = "GAM123";
string sdate = "05152014000000";
string edate = "05182014235959";
string node = "232641";
string group = "Al Ahsa - ???????";
string Compress = "";
string m_d = "sa";
string lang = "1";
DataSet ds = new DataSet();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
test_ws.ppppWebServiceSoapClient ws =
new test_ws.ppppWebServiceSoapClient("pppp Report Web ServiceSoap");
ds = ws.GetGroups(user, p1, p2);
DataSet ds_ra = new DataSet();
ds_ra = ws.RegionAlarm(user, p1, p2, sdate, edate, node, group, Compress, m_d, lang);
ds_ra.WriteXml("region_alarm.xml");
string connetionString = null;
SqlConnection connection;
SqlCommand command ;
SqlDataAdapter adpter = new SqlDataAdapter();
string sql = null;
string ID = null;
string nodegroup = null;
string nodecount = null;
connetionString = #"Server=.\SQLEXPRESS; DataBase=hhhh; Integrated Security=True;";
connection = new SqlConnection(connetionString);
int i = 0;
connection.Open();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
ID = ds.Tables[0].Rows[i].ItemArray[0].ToString();
nodegroup = ds.Tables[0].Rows[i].ItemArray[1].ToString();
nodecount = ds.Tables[0].Rows[i].ItemArray[2].ToString();
sql = "insert into groups (id,nodegroup,nodecount)
values(" + ID + ",'" + nodegroup + "'," + nodecount + ")";
command = new SqlCommand(sql, connection);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
}
sql = "select * from groups";
command = new SqlCommand(sql, connection);
adpter.SelectCommand = command;
adpter.SelectCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
adpter.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
MessageBox.Show("Done ..تم ");
}
}
}
After ensuring the NodeGroup column in your table is an NVARCHAR(), use parameters instead of concatenation, for both preventing SQL injection, and to make sure your data types are properly set. When you were concatenating the sql, the string literal was a varchar, unless you put an N in front of the literal.
sql = "insert into groups (id,nodegroup,nodecount)
values(#ID,#NodeGroup, #NodeCount)";
command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#ID", id);
command.Parameters.AddWithValue("#NodeGroup", nodegroup);
command.Parameters.AddWithValue("#NodeCroup", nodecount);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
Change this:
values(" + ID + ",'" + nodegroup + "'," + nodecount + ")";
into
values(" + ID + ", N'" + nodegroup + "'," + nodecount + ")";
However, you should really be using parameters instead of building an SQL string with the values in it. That will get you around all of the escaping issues.
When inserting in to database with inline sql you have to prefix the nvarchar value with 'N'. For example: insert into mytable (col1) values (N'myvalue')

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 + "'" ;
}

Programmatically acess Google chrome history

I want to index all the user actions and websites in google chrome. i understand that google chrome index all the data in sqlLite database. how can i Programmatically access the chrome web history in my own application
You need to download the appropriate assembly from the SqLite downloads page
Once you add a reference to the SQLite assembly, its very similar to standard ADO.net
All the user history is stored in the History database located at the path in the connection string below
SQLiteConnection conn = new SQLiteConnection
(#"Data Source=C:\Users\YourUserName\AppData\Local\Google\Chrome\User Data\Default\History");
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
// cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;";
// Use the above query to get all the table names
cmd.CommandText = "Select * From urls";
SQLiteDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Console.WriteLine(dr[1].ToString());
}
In Windows form application with Datagridview tool - button click event
private void button1_Click(object sender, EventArgs e)
{
string google = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + #"\Google\Chrome\User Data\Default\History";
string fileName = DateTime.Now.Ticks.ToString();
File.Copy(google, Application.StartupPath + "\\" + fileName);
using (SQLiteConnection con = new SQLiteConnection("DataSource = " + Application.StartupPath + "\\" + fileName + ";Versio=3;New=False;Compress=True;"))
{
con.Open();
//SQLiteDataAdapter da = new SQLiteDataAdapter("select url,title,visit_count,last_visit_time from urls order by last_visit_time desc", con);
SQLiteDataAdapter da = new SQLiteDataAdapter("select * from urls order by last_visit_time desc", con);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
con.Close();
}
try // File already open error is skipped
{
if (File.Exists(Application.StartupPath + "\\" + fileName))
File.Delete(Application.StartupPath + "\\" + fileName);
}
catch (Exception)
{
}
}
Reference source
Here i have copied the History file to Application startup path in order to avoid SQLite error "database is locked".
Used below code getting "Windows/x86_64" as a result
try
{
Class.forName ("org.sqlite.JDBC");
connection = DriverManager.getConnection ("jdbc:sqlite:/C:/Users/tarun.kakkar/AppData/Local/Google/Chrome/User Data/Default/History");
statement = connection.createStatement ();
resultSet = statement.executeQuery ("SELECT * FROM urls");
while (resultSet.next ())
{
System.out.println ("URL [" + resultSet.getString ("url") + "]" + ", visit count [" + resultSet.getString ("visit_count") + "]");
}
}
catch (Exception e)
{
e.printStackTrace ();
}
This piece of code might help you:
//Use sqlite for read chrome history
using System;
using System.IO;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
GetChromehistory();
Console.WriteLine();
}
public void GetChromehistory()
{
//Connection string
string path = #"\Google\Chrome\User Data\Default\History";
string chromehistorypath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + path;
if (File.Exists(chromehistorypath))
{
SQLiteConnection connection = new SQLiteConnection("Data Source=" + chromehistorypath + ";Version=3;New=False;Compress=True;");
connection.Open();
DataSet dataSet = new DataSet();
SQLiteDataAdapter adapter = new SQLiteDataAdapter("select * from urls order by last_visit_time desc", connection);
connection.Close();
adapter.Fill(dataSet);
var allHistoryItems = new List<ChromeHistoryItem>();
if (dataSet != null && dataSet.Tables.Count > 0 & dataSet.Tables[0] != null)
{
DataTable dt = dataSet.Tables[0];
foreach (DataRow historyRow in dt.Rows)
{
ChromeHistoryItem historyItem = new ChromeHistoryItem()
{
URL = Convert.ToString(historyRow["url"]),
Title = Convert.ToString(historyRow["title"])
};
// Chrome stores time elapsed since Jan 1, 1601 (UTC format) in microseconds
long utcMicroSeconds = Convert.ToInt64(historyRow["last_visit_time"]);
// Windows file time UTC is in nanoseconds, so multiplying by 10
DateTime gmtTime = DateTime.FromFileTimeUtc(10 * utcMicroSeconds);
// Converting to local time
DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(gmtTime, TimeZoneInfo.Local);
historyItem.VisitedTime = localTime;
allHistoryItems.Add(historyItem);
}
}
}
}
}
public class ChromeHistoryItem
{
public string URL { get; set; }
public string Title { get; set; }
public DateTime VisitedTime { get; set; }
}

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

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;
}
}

Categories