SQL connection problem when I try to use it 2 times - c#

I'm trying to create a project of an ATM where you have to enter the card number and pin but it's not working when I put the right pin says "Pin not found!" which is the catch but I copied the code from above and just changed what I thought necessary, does anyone know what's wrong?
static void Main()
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023;Database=atmbd;Trusted_Connection=True;"))
{
cn.Open();
string debitCard = "";
Console.WriteLine("Insert your card number: ");
while (true)
{
try
{
debitCard = Console.ReadLine();
if (debitCard.Length != 8)
{
Console.WriteLine("Wrong format!");
}
else
{
// falta algum IF EXISTS IN DB
using (var cmd = new SqlCommand() { Connection = cn, CommandText = "SELECT FirstName FROM atm WHERE CardNumber = '" + debitCard + "'" })
{
var reader = cmd.ExecuteReader();
if (reader.Read() == true)
{
Console.WriteLine("Hi, " + reader.GetString(0));
break;
}
else
{
Console.WriteLine("Not found");
}
}
}
}
catch
{
Console.WriteLine("Not found!");
}
}
string pin = "";
Console.WriteLine("Insert pin ");
while (true)
{
try
{
pin = Console.ReadLine();
using (var cmd = new SqlCommand() { Connection = cn, CommandText = "SELECT FirstName, LastName FROM atm WHERE Pin = '" + pin + "'" })
{
var reader = cmd.ExecuteReader();
if (reader.Read() == true)
{
Console.WriteLine("User Found");
break;
}
else
{
Console.WriteLine("Not found!");
}
}
}
catch
{
Console.WriteLine("Pin not found!");
}
}
}
}
I've tried many different ways and I can't do it. If anyone can help me, I'd be grateful

There are many issues in your existing code. Let me highlight few of them.
You should use parameterized query, you code is open to SQL Injection.
I don’t know why are you storing card number and pin in your database tables. It’s against PCIDSS standards, you need to read about it.
You cannot store the card number as plain text, I don’t know about current standards, but earlier it was that you should mask the card while storing and now I think it’s token based ( at lest in india now).
And you can’t at all store the PIN number in database as plain text.
You need to store the encrypted PIN number.
And there is no one-one mapping for your card number and pin. Because same pin can be used by many people, so you need one-one mapping as well.
You should simplify your query to IF EXISTS SELECT 1 FROM …
If you simplify your code then you will realize that you need to rerun only one item from database, so you could use ExecuteScalar for the same.
And last but not the least, put breakpoint and debug your code.

Currently, your catch block not taking exception object. So it is difficult to find the exact root cause of this issue. So change your catch block as below
catch(Exception ex) { Console.WriteLine(ex.Message); }
From the exception object, you will get the exact root cause of your issue.

Related

c# odbcDatareader get the duplicated field value

I have a strange problem:
Database: Firebird
Connection String:
Driver={Firebird/InterBase(r)driver};Dbname=xxx;CHARSET=NONE;UID=xxx;
PASSWORD=xxx
I use a set of ODBC classes to operation(select) the database table
when I loop the db records with OdbcDataReader.GetValue(), if some fields(char type) have no value(char_length()=0), it would get the last record field value; if fields has the value, it's ok(does not get the value from last record)
My code likes below:
var dr = this.SqlExecutor.Open(sql); //sql is String variable that stored the sql statement
while (dr.Read())
{
this.Logger.Info("-----Customer_Id: " + this.SqlReader.GetFieldAsString(dr, "Customer_Id") + " -----"); // this not duplicated because it's not empty
this.Logger.Info("-----Customer_Email: " + this.SqlReader.GetFieldAsString(dr, "Customer_email") + " -----"); //this would if some records has empty value
}
// the method SqlExecutor.Open(sql) and SqlReader.GetFieldAsString() please refer to below:
public IDataReader Open(string sql)
{
this.Logger.Debug("sql: " + sql);
if (this.reader != null && !this.reader.IsClosed)
{
this.reader.Close();
this.reader = null;
}
try
{
this.cmdForSelect.Connection = this.conn;
this.cmdForSelect.CommandTimeout = 120;
this.cmdForSelect.CommandText = sql;
this.cmdForSelect.Parameters.Clear();
foreach (var p in this.dbParameters)
{
this.cmdForSelect.Parameters.Add(p);
}
this.reader = cmdForSelect.ExecuteReader();
}
catch (Exception ex)
{
this.Logger.Error("There is an error: {0}", ex.Message);
this.Logger.Info("Error sql query:" + sql);
throw;
}
finally
{
this.ClearParameters();
}
return this.reader;
}
public string GetFieldAsString(IDataReader dr, string fieldName)
{
try
{
var value = dr.GetValue(dr.GetOrdinal(fieldName));
if (value == DBNull.Value)
{
return string.Empty;
}
return Convert.ToString(value);
}
catch
{
return string.Empty;
}
}
Besides, this case is fine on my computer, just happened on my customer's computer, I feel this does not matter with mycode, anyone know this, please help me, thanks a lot!!!
Assuming the actual code is not posted in your question; I think the problem is with re-initiation of the variable in the actual code. You need to revisit the code and check the IF-ELSE condition you have applied on the this.SqlReader.GetFieldAsString(dr, "Customer_email")

C# Webservice stucks. Need to override published file to restart

Please help me, I'm facing a fatal problem here. If someone could fix this, I swear I will treat u to a huge drink whenever u step into my country (Vietnam). Ok here's the problem: I'm coding a webservice for multi connection simultaneously from tablet (around 100 clients). It ran well but recently whenever high traffic occurs, my webservice seems to stuck somehow and I need to copy - override the published file of webservice in order for it to run again (restart website in IIS is no use) ...
This is my w/s code for handling the data:
public string Info_Handling(string id, string name, string strDetails)
{
string checkExist = "";
string str = "";
string str2 = "";
MLL_Customer _customerClient = new MLL_Customer();
MLL_CustomerCategory _categoryClient = new MLL_CustomerCategory();
MLL_Product _productClient = new MLL_Product();
MLL_SampleProduct _sampleClient = new MLL_SampleProduct();
if (_customerClient.CheckExistCustomer(id, name.ToUpper(), 2) == 1) // SID & NAME
{
checkExist = "EXIST";
}
using (SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["Main.ConnectionString"]))
{
connection.Open();
SqlTransaction trans = connection.BeginTransaction("XXX");
try
{
// ID Example: 11 means VIP - 12 means Normal - 13 means ples... jkg
// First - Insert Customer
string strCustomerCategory = _categoryClient.SelectCategoryByID(id).ToString();
if (!checkExist.Equals("EXIST"))
{
Customer businessObject = new Customer();
businessObject.ID = sid;
businessObject.Name = name.ToUpper();
businessObject.CategoryID = strCustomerCategory;
str = "" + _customerClient.Insert(businessObject, connection, trans);
}
// Second Insert Product spliting from a string Ex: "TV&Laptop&CD"
string[] productDetails = strDetails.Split(new char[] { '&' });
object obj3;
SampleProduct objSample;
Product objProduct;
for (int j = 0; j < productDetails.Length; j++)
{
if (_productClient.CheckExist(id, productDetails[j])) == null) // Check if customer already owns this product
{
// Get the properties of sample product.
objSample = _sampleClient.SelectSampleProduct(productDetails[j]);
objProduct = new Product();
objProduct.SID = sid;
objProduct.Testcode = objSample.TestCode;
objProduct.Category = objSample.Category;
objProduct.Unit = objSample.Unit;
objProduct.Price = objSample.Price;
if (_productClient.Insert(objProduct, connection, trans) != 0)
{
str2 = str2 + "&" + objProduct.Testcode;
// return the code of product in order to see which product has been inserted successfully
}
}
}
trans.Commit();
SqlConnection.ClearAllPools();
}
catch (Exception exception)
{
str = "0";
str2 = exception.Message + exception.Source;
try
{
trans.Rollback();
}
catch (Exception)
{
}
}
}
if (!str2.Equals(""))
{
return (str + "&" + id + str2);
}
return ("0&" + sid + str);
}
I modified the code but this is basically how i roll. Could anyone plz tell me some solution. Deeply thank u.
1 more thing about ClearAllPools() method: I know how it works but I dont even know why I need it. Without this, my data will be messed up terrible. CategoryID of one customer will be assigned for another customer sometimes. ???? How could it happened ?? HELP

Int.TryParse not resolving specified cast is not valid error

Alright I originally started out using a Convert.ToInt32(myradTextBox.Text) then it said specified cast is not valid. I did some research on here and decided to try Int.TryParse. Upon doing so I still received this error. What I am trying to do is when the user enters an ID and hits the create button, it searches the DB to see if that ID is already there. I have also tried to convert the bool value from my Int.TryParse to int using Convert.ToInt32(Result) still same error (see below in third code post for where that would be posted). Maybe it has something to do with my comparison method.
Below I have provided the Int.TryParse method with values. The Method I am calling to check the userinput is not in the db currently and my if statement that is catching the statement. Any input on how to fix this would be greatly appreciated. I am still new to most of this stuff so I apologize if leaving any critical info off. Just ask if you need clarification or something elaborated.
Here is my method for comparison:
public bool isValidID(int id)
{
SqlConnection dbConn = null;
int count = 0;
try
{
using (dbConn = new SqlConnection(Properties.Settings.Default["tville"].ToString()))
{
string sql = "SELECT Count(*) FROM PackLabelFormat where PackFormatID = #PackFormatID";
SqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#PackFormatID", id);
dbConn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
count = reader.GetInt16(0);
}
}
}
catch (Exception ex)
{
throw ex;
}
if (count > 0)
return false;
return true;
}
Here is my variables that I use in my Int.TryParse method:
string IDselect = rTxtBoxFormatID.Text.ToString();
int resultInt;
bool result = int.TryParse(IDselect, out resultInt);
Lastly here is my method that is catching the error:
SqlConnection dbConn = null;
LabelData labelList = new LabelData();
try
{
using (dbConn = new SqlConnection(Properties.Settings.Default["tville"].ToString()))
{
if (SelectedVersion.isValidID(resultInt))
{
SelectedVersion.PackFormatID = resultInt;
}
else
{
MessageBox.Show("ID already in use!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (Exception ex)
{
throw ex;
}
The database column did not support Int16 aka short. Which was why my specified cast is not valid error never went away no matter what I tried. Thank you for your help in this matter! Here is the code to further illustrate what the problem was.
using (SqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
//count = reader.GetInt16(0); needs to be reader.GetInt32(0);
}

Should I refactor this, or is my confusion cause to be cautious? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
This SqlCe code looks awfully strange to me:
cmd.CommandText = "INSERT INTO departments ( account_id, name) VALUES (?, ?)";
foreach(DataTable tab in dset.Tables)
{
if (tab.TableName == "Departments")
{
foreach(DataRow row in tab.Rows)
{
Department Dept = new Department();
if (!ret)
ret = true;
foreach(DataColumn column in tab.Columns)
{
if (column.ColumnName == "AccountID")
{
Dept.AccountID = (string) row[column];
}
else if (column.ColumnName == "Name")
{
if (!row.IsNull(column))
Dept.AccountName = (string) row[column];
else
Dept.AccountName = "";
}
}
List.List.Add(Dept);
. . .
dSQL = "INSERT INTO departments ( account_id, name) VALUES ('" + Dept.AccountID + "','" + Dept.AccountName +"')";
if (!First)
{
cmd.Parameters[0].Value = Dept.AccountID;
cmd.Parameters[1].Value = Dept.AccountName;
}
if (First)
{
cmd.Parameters.Add("#account_id",Dept.AccountID);
cmd.Parameters.Add("name",Dept.AccountName);
cmd.Prepare();
First = false;
}
if (frmCentral.CancelFetchInvDataInProgress)
{
ret = false;
return ret;
}
try
{
dbconn.DBCommand( cmd, dSQL, true );
}
. . .
public void DBCommand(SqlCeCommand cmd, string dynSQL, bool Silent)
{
SqlCeTransaction trans = GetConnection().BeginTransaction();
cmd.Transaction = trans;
try
{
cmd.ExecuteNonQuery();
trans.Commit();
}
catch (Exception ex)
{
try
{
trans.Rollback();
}
catch (SqlCeException)
{
// Handle possible exception here
}
MessageBox.Show("DBCommand Except 2"); // This one I haven't seen...
WriteDBCommandException(dynSQL, ex, Silent);
}
}
My questions are:
1) Should "?" really be used in the assignment to cmd.CommandText, or should "#" be used instead?
2) One of the "cmd.Parameters.Add()"s (account_id) uses a "#" and the other (name) doesn't. Which way is right, or is the "#" optional?
3) I can't make heads or tails of why DBCommand() is written as it is - the final two args are only used if there's an exception...???
I'm tempted to radically refactor this code, because it seems so bizarre, but since I don't really understand it, that might be a recipe for disaster...
I'm fairly certain this article will answer some of your questions:
http://msdn.microsoft.com/en-us/library/yy6y35y8.aspx
The second chart explains the difference between the named and positional (?) parameters (used in OleDb and ODBC).
I believe in the case where the ? is used, the # is optional, but I'm not sure of this. If it's working, I'd say that that IS the case.
The stuff in DBCommand appears to simply be there for logging purposes. If the exection fails, it tries to do a rollback and then logs the exception with the sql command (in dynSQL).
The ? parameter is older Access syntax.
My guess is this used to be an Access database, but someone converted it to SQL CE at some point.
Generally, SQL understands that ? parameter, but it's better to just change that while you are in there so that it is more understood.
I'm still trying to make heads & tails of all these variables. If I get it sorted out, I'll post up compilable (sp?) code.
EDIT: I had to put this into a method and work out all of the RED errors to make sure I wasn't giving you something that would not compile.
I passed it your DataSet like so, with lots of comments added:
private bool StrangeSqlCeCode(DataSet dset) {
const string ACCOUNT_ID = "AccountID";
const string DEPARTMENTS = "Departments";
const string NAME = "Name";
const string SQL_TEXT = "INSERT INTO departments (account_id, name) VALUES (#account_id, #name)";
bool ret = false;
//bool First = false; (we don't need this anymore, because we initialize the SqlCeCommand correctly up front)
using (SqlCeCommand cmd = new SqlCeCommand(SQL_TEXT)) {
// Be sure to set this to the data type of the database and size field
cmd.Parameters.Add("#account_id", SqlDbType.NVarChar, 100);
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 100);
if (-1 < dset.Tables.IndexOf(DEPARTMENTS)) {
DataTable tab = dset.Tables[DEPARTMENTS];
foreach (DataRow row in tab.Rows) {
// Check this much earlier. No need in doing all the rest if a Cancel has been requested
if (!frmCentral.CancelFetchInvDataInProgress) {
Department Dept = new Department();
if (!ret)
ret = true;
// Wow! Long way about getting the data below:
//foreach (DataColumn column in tab.Columns) {
// if (column.ColumnName == "AccountID") {
// Dept.AccountID = (string)row[column];
// } else if (column.ColumnName == "Name") {
// Dept.AccountName = !row.IsNull(column) ? row[column].ToString() : String.Empty;
// }
//}
if (-1 < tab.Columns.IndexOf(ACCOUNT_ID)) {
Dept.AccountID = row[ACCOUNT_ID].ToString();
}
if (-1 < tab.Columns.IndexOf(NAME)) {
Dept.AccountName = row[NAME].ToString();
}
List.List.Add(Dept);
// This statement below is logically the same as cmd.CommandText, so just don't use it
//string dSQL = "INSERT INTO departments ( account_id, name) VALUES ('" + Dept.AccountID + "','" + Dept.AccountName + "')";
cmd.Parameters["#account_id"].Value = Dept.AccountID;
cmd.Parameters["#name"].Value = Dept.AccountName;
cmd.Prepare(); // I really don't ever use this. Is it necessary? Perhaps.
// This whole routine below is already in a Try/Catch, so this one isn't necessary
//try {
dbconn.DBCommand(cmd, true);
//} catch {
//}
} else {
ret = false;
return ret;
}
}
}
}
return ret;
}
I wrote an overload for your DBCommand method to work with Legacy code:
public void DBCommand(SqlCeCommand cmd, string dynSQL, bool Silent) {
cmd.CommandText = dynSQL;
DBCommand(cmd, Silent);
}
public void DBCommand(SqlCeCommand cmd, bool Silent) {
string dynSQL = cmd.CommandText;
SqlCeTransaction trans = GetConnection().BeginTransaction();
cmd.Transaction = trans;
try {
cmd.ExecuteNonQuery();
trans.Commit();
} catch (Exception ex) {
try {
trans.Rollback(); // I was under the impression you never needed to call this.
// If Commit is never called, the transaction is automatically rolled back.
} catch (SqlCeException) {
// Handle possible exception here
}
MessageBox.Show("DBCommand Except 2"); // This one I haven't seen...
//WriteDBCommandException(dynSQL, ex, Silent);
}
}

Relationship in XAMPP between two tables and inserting data into each in c#

I have a question that I can't seem to figure out. I'm creating an application that adds a client's information then relate it to a service that is being provided. I created the relationship between the two tables in xampp database. The tables are tclientinfo and tserviceinfo. The columns in the tclientinfo table are Client_ID(PK), First_Name, Last_Name, Phone, and Email. In the tserviceinfo, Service_Order, Date, Tech, Brand, Model, OS, Type, PC_Issue, Service, Service_Price, Total_Price, Service_Notes, Client_ID. Client_ID is what I'm using as the relationship, but I am unable to add information to the tserviceinfo table. I'm getting the SQL exception: Cannont add or update a child row: a foreign key constraint fails('dbocomputerinformation'.'tserviceinfo',CONSTRAINT 'tserviceinfo_ibfk_3' FOREIGN KEY('Client_ID') REFERENCES 'tclientinfo' ('Client_ID') ON DELETE CASCADE ON UPDATE CASCADE).
My add button to insert information into tclientinfo is:
private void btnAdd_Click(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection("server=localhost;uid=root;password=Passwordwhatever;database=dbocomputerinformation;");
conn.Open();
string email = tbEmail.Text;
string date = tbDate.Text;
//try statement for validation before sending to database.
try
{
if (tbFirstName.Text.Length == 0)
{
MessageBox.Show("Please enter in customer's first name.");
this.tbFirstName.Focus();
return;
}
if (tbLastName.Text.Length == 0)
{
MessageBox.Show("Please enter in customer's last name.");
this.tbLastName.Focus();
return;
}
if (tbPhone.Text.Length < 10)
{
MessageBox.Show("Phone number must be ten digits.");
this.tbPhone.Focus();
return;
}
if (tbPhone.Text.Length == 0)
{
MessageBox.Show("Please enter in customer's phone number.");
this.tbPhone.Focus();
return;
}
if (tbPhone.Text != string.Empty && !Regex.IsMatch(tbPhone.Text, #"^[0-9]+$"))
{
MessageBox.Show("Please enter in numbers only.");
this.tbPhone.Focus();
return;
}
if (tbEmail.Text.Length == 0)
{
MessageBox.Show("Please enter in customer's email.");
this.tbEmail.Focus();
return;
}
if (email.IndexOf('#') == -1 || email.IndexOf('.') == -1)
{
MessageBox.Show("Please enter a valid email address.");
this.tbEmail.Focus();
return;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
try
{
MySqlCommand command = new MySqlCommand("Insert into tclientinfo (First_Name, Last_Name, Phone, Email) values (?First_Name, ?Last_Name, ?Phone, ?Email)", conn);
command.Parameters.AddWithValue("?First_Name", tbFirstName.Text);
command.Parameters.AddWithValue("?Last_Name", tbLastName.Text);
command.Parameters.AddWithValue("?Phone", tbPhone.Text);
command.Parameters.AddWithValue("?Email", tbEmail.Text);
command.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Client Added Successfully.");
}
catch (MySqlException ex)
{
MessageBox.Show("Can't connect to database\n" + ex.ToString());
}
}
Then my insert into tserviceinfo is:
private void btnCreate_Click(object sender, EventArgs e)
{
//string connString = "server=localhost;uid=root;password=Passwordwhatever;database=dbocomputerinfo;";
MySqlConnection conn = new MySqlConnection("server=localhost;uid=root;password=Passwordwhatever;database=dbocomputerinfo;");
conn.Open();
string date = tbDate.Text;
//try statement for validation before sending to database.
try
{
if (tbDate.Text.Length == 0)
{
MessageBox.Show("Please enter in date of service.");
this.tbDate.Focus();
return;
}
if (date.IndexOf('-') == -2)
{
MessageBox.Show("Please enter correct date. mm-dd-yy.");
this.tbDate.Focus();
return;
}
if (tbTech.Text.Length == 0)
{
MessageBox.Show("Please enter in service technician.");
this.tbTech.Focus();
return;
}
if (tbBrand.Text.Length == 0)
{
MessageBox.Show("Please enter in customer's brand of computer.");
this.tbBrand.Focus();
return;
}
if (tbModel.Text.Length == 0)
{
MessageBox.Show("Please enter in computer model.");
this.tbModel.Focus();
return;
}
if (tbOS.Text.Length == 0)
{
MessageBox.Show("Please enter in computer's operating system.");
this.tbOS.Focus();
return;
}
if (rbDesktop.Checked == false && rbNotebook.Checked == false)
{
MessageBox.Show("Please select device type.");
this.rbDesktop.Focus();
return;
}
if (lvOrdered.Items.Count == 0)
{
MessageBox.Show("Please select a service.");
this.lvServices.Focus();
return;
}
if (tbIssue.Text.Length == 0)
{
MessageBox.Show("Please describe the issue with the computer.");
this.tbIssue.Focus();
return;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
try
{
MySqlCommand command = new MySqlCommand("Insert into tserviceinfo (Date, Tech, Brand, Model, OS, Type, PC_Issue, Service, Service_Price, Total_Price) values (?Date, ?Tech, ?Brand, ?Model, ?OS, ?Type, ?PC_Issue, ?Service, ?Service_Price, ?Total_Price)", conn);
command.Parameters.AddWithValue("?Date", tbDate.Text);
command.Parameters.AddWithValue("?Tech", tbTech.Text);
command.Parameters.AddWithValue("?Brand", tbBrand.Text);
command.Parameters.AddWithValue("?Model", tbModel.Text);
command.Parameters.AddWithValue("?OS", tbOS.Text);
command.Parameters.AddWithValue("?PC_Issue", tbIssue.Text);
/**
* Was having issues inserting a single service, it would dublicate itself in the db, this was the solution
* this adds just a single service with nothing else, and it reads back properly as well.
**/
if (lvOrdered.Items.Count == 1)
{
string singleService = string.Join(" ", services);
command.Parameters.AddWithValue("?Service", singleService);
}
else
{
/**
* Combine all the services into one string seperated by commas
* and add that to the database
* */
string serviceList = string.Join(", ", services);
command.Parameters.AddWithValue("?Service", serviceList);
}
/**
* Combine all the prices into one string seperated by commas
* and add that to the database
* */
string servicePriceList = string.Join(", ", servicePrice);
command.Parameters.AddWithValue("?Service_Price", servicePriceList);
command.Parameters.AddWithValue("?Total_Price", lblPrice.Text);
//clears lists so dublicates don't happen when creating more work orders than just 1.
services.Clear();
servicePrice.Clear();
if (rbDesktop.Checked)
{
command.Parameters.AddWithValue("?Type", "Desktop");
}
else if (rbNotebook.Checked)
{
command.Parameters.AddWithValue("?Type", "Notebook");
}
command.ExecuteNonQuery();
conn.Close();
tbFirstName.Clear();
tbLastName.Clear();
tbDate.Clear();
tbEmail.Clear();
tbBrand.Clear();
tbIssue.Clear();
tbTech.Clear();
tbModel.Clear();
tbPhone.Clear();
tbOS.Clear();
lvOrdered.Items.Clear();
lblPrice.Text = "$0.00";
}
catch (MySqlException ex)
{
MessageBox.Show("Can't connect to database\n" + ex.ToString());
}
}
So needless to say, I'm not positive on what to do from here. Any help would be awesome or any ideas. If you need anymore information, let me know. Thanks!
Figured it out guys, sorry for being dumb. But I needed to select the Client_ID and store it as a variable. Then insert it into the second table.
So like this if anyone else has this question ever.
intMaxClientId;
MySqlCommand command = new MySqlCommand("Select max(Client_ID) from tclientinfo", conn);
maxClientId = Convert.ToInt32(command.ExecuteScalar());
command.Parameters.AddWithValue("?Client_ID", maxClientId);

Categories

Resources