recently stored data cannot be read by another method - c#

I have added the data as:
public static void insert()
{
try
{
string connStr =
(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\test.accdb;Persist Security Info=False");
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = connStr;
OleDbCommand cmd = conn1.CreateCommand();
cmd.CommandText =
"INSERT INTO patientinfo (medicareNo, title, fName, lName, gender, height, weight, age )" +
" VALUES(" + p.getMedicare() + ",'" + p.getTitle() + "','" + p.getfName() + "','" + p.getlName() +
"','" + p.getGender() + "'," + p.getheight() + "," + p.getweight() + "," + p.getAge() + ");";
conn1.Open();
cmd.ExecuteNonQuery();
//displayResult(medicareNo);
}
catch (OleDbException exp)
{
Console.WriteLine("Error");
}
displayResult(medicareNo);
}
and I have another method for reading data
public static void displayResult(int medicareNo )
{
try
{
string connStr =
(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\test.accdb;Persist Security Info=False");
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = connStr;
OleDbCommand cmd1 = conn1.CreateCommand();
cmd1.CommandText = "SELECT * FROM patientinfo WHERE medicareNo = " + "" + medicareNo + "";
conn1.Open();
OleDbDataReader rdr = null;
rdr = cmd1.ExecuteReader();
if (rdr.HasRows)
{
checkvalue = true;
foreach (DataRow row in rdr.GetSchemaTable().Rows)
{
Console.Write(row["ColumnName"].ToString() + " ");
}
Console.WriteLine(" ");
while (rdr.Read())
{
Console.Write(rdr["medicareNo"].ToString());
Console.Write(" ");
Console.Write(rdr["title"].ToString());
Console.Write(" ");
Console.Write(rdr["fName"].ToString());
Console.Write(" ");
Console.Write(rdr["lName"].ToString());
Console.Write(" ");
Console.Write(rdr["gender"].ToString());
Console.Write(" ");
Console.Write(rdr["height"].ToString());
Console.Write(" ");
Console.Write(rdr["weight"].ToString());
Console.Write(" ");
Console.WriteLine(rdr["age"].ToString());
Console.WriteLine(".......................");
}
Console.WriteLine("Patient registered. Information retrieved. ");
}
else
{
checkvalue = false;
Console.WriteLine("Patient not registered. Add Patient information for registration.");
}
}
catch (OleDbException exp)
{
Console.WriteLine("error.");
}
}
The problem is displayResult() cannot find the recently added data, so i cannot display it right after adding it. Even calling them separately in main() didnt work. It just goes to "patient not registered..................".Any suggestions please
update: get set method for medicareno.
public void SetMedicare(int pMedicare)
{
if (pMedicare > 0)
{
medicareNo = pMedicare;
}
else
{
Console.WriteLine("Medicare Number not valid");
}
}
public int getMedicare()
{
return medicareNo;
}

Your SELECT statement is the issue:
"SELECT * FROM patientinfo WHERE medicareNo = " + "" + medicareNo + ""
It is comparing medicareNo as a string, instead of as an int.
Change your query to this:
"SELECT * FROM patientinfo WHERE medicareNo = " + medicareNo

change displayResult(medicareNo); with below
displayResult(p.getMedicare());
And also I would change your methods as below
public static void insert()
{
try
{
string connStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\test.accdb;Persist Security Info=False";
string commandText = "INSERT INTO patientinfo (medicareNo, title, fName, lName, gender, height, weight, age )" +
" VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
using (OleDbConnection con = new OleDbConnection(connStr))
using (OleDbCommand cmd = new OleDbCommand(commandText, con))
{
cmd.Parameters.AddWithValue("#medicareNo", p.getMedicare());
cmd.Parameters.AddWithValue("#title", p.getTitle());
cmd.Parameters.AddWithValue("#fName", p.getfName());
cmd.Parameters.AddWithValue("#lName", p.getlName());
cmd.Parameters.AddWithValue("#gender", p.getGender());
cmd.Parameters.AddWithValue("#height", p.getheight());
cmd.Parameters.AddWithValue("#weight", p.getweight());
cmd.Parameters.AddWithValue("#age", p.getAge());
con.Open();
int ret = cmd.ExecuteNonQuery();
if(ret ==1)
Console.WriteLine("Insert Successful");
}
displayResult(p.getMedicare());
}
catch (OleDbException exp)
{
Console.WriteLine("Error");
}
}
public static void displayResult(int medicareNo)
{
try
{
string connStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\test.accdb;Persist Security Info=False";
string commandText = "SELECT * FROM patientinfo WHERE medicareNo = ?";
using (OleDbConnection con = new OleDbConnection(connStr))
using (OleDbCommand cmd = new OleDbCommand(commandText, con))
{
cmd.Parameters.AddWithValue("#medicareNo", medicareNo);
con.Open();
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
foreach (DataRow row in rdr.GetSchemaTable().Rows)
{
Console.Write(row["ColumnName"].ToString() + " ");
}
Console.WriteLine(" ");
while (rdr.Read())
{
string str = string.Format("{0} {1} {2} {3} {4} {5} {6} {7}",
rdr["medicareNo"], rdr["title"], rdr["fName"], rdr["lName"],
rdr["gender"], rdr["height"], rdr["weight"], rdr["age"]);
Console.WriteLine(str);
}
Console.WriteLine("Patient registered. Information retrieved. ");
}
else
{
Console.WriteLine("Patient not registered. Add Patient information for registration.");
}
}
}
}
catch (OleDbException exp)
{
Console.WriteLine("error.");
}
}

Related

How can I add some values into my database

I'm a beginner in C# and I wrote a code that connect to my database but It give me a error
I did everything from first but nothing happened
private void btnSubmit_Click(object sender, EventArgs e)
{
string conString = "data source=DESKTOP-D5VFL9P; initial catalog = university; integrated security = True; MultipleActiveResultSets = True;";
using (SqlConnection connection = new SqlConnection(conString))
{
connection.Open();
using(SqlCommand command = new SqlCommand("INSERT INTO Persons (PersonID, LastName, FirstName, Age, City) VALUES (" + int.Parse(txtPersonID.Text) + ", '" +
txtLastName.Text + "', '" + txtFirstName.Text + "' ," + int.Parse(txtAge.Text) + ", '" + txtCity.Text + "'", connection))
{
using(SqlDataReader reader = command.ExecuteReader())
{
MessageBox.Show("Data inserted");
txtFirstName.Text = "";
txtLastName.Text = "";
txtPersonID.Text = "";
txtAge.Text = "";
txtCity.Text = "";
}
}
}
}
I want to add some values to my database
There should be a ) behind the City. Like txtCity.Text + "')".
I am not recommending this as it is definitely opens a door for SQL Injection Attack but Use below string that will work in your case:
string cmdText = "INSERT INTO Persons(PersonID,LastName,FirstName,Age,City)" +
" VALUES ('" + int.Parse(txtPersonID.Text) + "', " +
"'" + txtLastName.Text + "', " +
"'" + txtFirstName.Text + "' ,'" +
int.Parse(txtAge.Text) + "', '" +
txtCity.Text + "')"
I would do something like this:
using (SqlConnection conn = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"INSERT INTO Persons (PersonID,LastName,FirstName,Age,City) VALUES (#PersonID,#LastName,#FirstName,#Age,#City)";
cmd.Parameters.AddWithValue("#PersonID", int.Parse(txtPersonID.Text));
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
cmd.Parameters.AddWithValue("#City", txtCity.Text);
cmd.Connection = conn;
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
if(rowsAffected > 0)
{
MessageBox.Show("Data inserted");
}
else
{
MessageBox.Show("Failed");
}
conn.Close();
}

sqlite database is locked C#

So i have this "database is locked" exception since yesterday. Tried everything i found here, yet still nothing. I'm using two forms - simple login form and then another one, where user can add new product to database. Checking if product already exist in db works, but adding new one throws that exception. Check it out please:
try
{
using (SqliteConnection db = new SqliteConnection("Filename=Magazyn.sqlite"))
{
db.Open();
string SQLcheck = "select * from Administrator";
using (SqliteCommand cmd = new SqliteCommand(SQLcheck, db))
{
using (SqliteDataReader reader = cmd.ExecuteReader())
{
var count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count > 0 && textBox1 != null && !string.IsNullOrWhiteSpace(textBox1.Text))
{
string sql = "select * from Administrator WHERE Name='" + textBox1.Text +
"' AND Password ='" + textBox2.Text + "'";
using (SqliteCommand command = new SqliteCommand(sql, db))
{
using (SqliteDataReader rdr = command.ExecuteReader())
{
if (rdr.Read())
{
MessageBox.Show(textBox1.Text + ", zostałeś pomyślnie zalogowany", "Logowanie");
AddProduct a = new AddProduct();
a.ShowDialog();
this.Close();
return;
}
else
{
MessageBox.Show("Nie ma administratora o loginie " + textBox1.Text +" lub Twoje hasło jest niepoprawne", "Błąd logowania");
textBox1.Clear();
textBox2.Clear();
}
}
}
}
else if (count == 0)
{
MessageBox.Show(
"W systemie nie istnieje konto administratora - nastąpi przekierowanie do formularza rejestracyjnego",
"Pierwsze logowania - konieczna rejestracja");
AddAdmin a = new AddAdmin();
a.ShowDialog();
return;
}
}
}
db.Close();
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
And 2nd Form:
try
{
using (SqliteConnection db = new SqliteConnection("Filename = Magazyn.sqlite"))
{
db.Open();
string sqlCheck = "select * from Produkty WHERE RFID='" + RFID.Text + "'";
using (SqliteCommand cmd = new SqliteCommand(sqlCheck, db))
{
using (SqliteDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
MessageBox.Show("W bazie produktów jest już produkt o podanym tagu RFID", "Wykryto duplikat");
RFID.Clear();
}
else
{
reader.Close();
reader.Dispose();
string sql = "INSERT INTO Produkty (Name, RFID, Price, Unit, VAT) values ('" + Nazwa.Text + "','" +
RFID.Text + "','" + Cena.Text + "','" + Jednostka.Text + "','" + VATcat + "');";
//string sql = #"INSERT INTO Produkty (Name, RFID, Price, Unit, VAT) values (#name, #RFID, #price, #unit, #vat)";
using (SqliteCommand command = new SqliteCommand(sql, db))
{
using (SqliteDataReader rdr = command.ExecuteReader())
{
MessageBox.Show("Pomyślnie dodano produkt " + Nazwa.Text + " do bazy danych", "Dodano produkt");
}
/* command.CommandText = sql;
command.Connection = db;
command.Parameters.Add(new SqliteParameter("#name", Nazwa.Text));
command.Parameters.Add(new SqliteParameter("#RFID", RFID.Text));
command.Parameters.Add(new SqliteParameter("#price", Cena.Text));
command.Parameters.Add(new SqliteParameter("#unit", Jednostka.Text));
command.Parameters.Add(new SqliteParameter("#vat", VATcat));
command.ExecuteNonQuery();
MessageBox.Show("Pomyślnie dodano produkt " + Nazwa.Text + " do bazy danych", "Dodano produkt");
*/
}
}
}
}
db.Close();
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
I commented another way of adding to db (Will test both when I get rid of that exception)
Funny thing that if i change INSERT to SELECT it's working. If I use INSERT query directly in database file it's working too.

how can i merge two field in combobox

this is my code :
cmbSahebFa.Items.Clear();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select mID,mName from tblMoshtari";
objCon.Connecting();
cmd.Connection = objCon.con;
objCon.con.Open();
try
{
SqlDataReader objDataReader = cmd.ExecuteReader();
object[] x = new object[2];
while (objDataReader.Read())
{
objDataReader.GetSqlValues(x);
cmbSahebFa.Items.Add(x[1].ToString());
}
}
catch (Exception exp)
{
MessageBox.Show("Error") : " + exp.Message);
}
finally
{
objCon.con.Close();
}
i want to display both field in combo box.
how can i show two field mID+mName in combobox ?
cmbSahebFa.Items.Add(objDataReader[0].ToString() + " " + objDataReader[1].ToString());
or
SqlDataReader objDataReader = cmd.ExecuteReader();
object[] x = new object[2];
while (objDataReader.Read())
{
objDataReader.GetSqlValues(x);
cmbSahebFa.Items.Add(x[0].ToString()+ " " + x[1].ToString());
}
or by column name
SqlDataReader objDataReader = cmd.ExecuteReader();
while (objDataReader.Read())
{
cmbSahebFa.Items.Add(objDataReader["mID"].ToString() + " " + objDataReader["mName"].ToString());
}
Here is MSDN Reference on Retrieving Data Using DataReader.
I think, SQL concatination would be easier:
cmd.CommandText = "select mID + ' ' + mName from tblMoshtari";

input string was not in a correct format c# datetimepicker

private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (_action == "edit")
{
update(_id, int.Parse(cbSupplier.ValueMember), dtpTRXdate.Value.ToString("yyyy-MM-dd"), dtpDUEdate.Value.ToString("yyyy-MM-dd"), txtRemarks.Text.ToString(), _conn);
}
else
{
insert(int.Parse(cbSupplier.ValueMember), dtpTRXdate.Value.ToString("yyyy-MM-dd"), dtpDUEdate.Value.ToString("yyyy-MM-dd"), txtRemarks.Text.ToString(), _conn);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void insert(int sup_ID, string TRX_date, string DUE_date, string remarks, MySqlConnection conn)
{
MessageBox.Show(sup_ID.ToString() + " " + TRX_date + " " + DUE_date + " " + remarks);
MySqlCommand command = new MySqlCommand();
command.Connection = conn;
command.CommandText = "INSERT INTO PO_HEADER VALUES(null," + sup_ID + ",'" + TRX_date + "','" + DUE_date + "','" + remarks + "')";
command.ExecuteNonQuery();
}
public void update(int id, int sup_id, string trx_date, string due_date, string remarks, MySqlConnection conn)
{
MySqlCommand command = new MySqlCommand();
command.Connection = conn;
command.CommandText = "UPDATE PO_HEADER SET SUPPLIER_ID=" + sup_id + ", TRX_DATE='" + trx_date + "', DUE_DATE='" + due_date + "', REMARKS='" + remarks + "' WHERE ID=" + id;
command.ExecuteNonQuery();
}
dtpTRXdate it's datetimepicker
the problem at : dtpTRXdate.Value.ToString("yyyy-MM-dd") and dtpDUEdate.Value.ToString("yyyy-MM-dd")
when i click button save and run the function, it say "input string was not in a correct format"
i messagebox the string it's true, example : "2012-12-12"
have any idea???
Problem : You are sending the Date value selected from DateTimePicker control after converting into string as yyyy-MM-dd, but in database table the datatype might be Date so it takes Date and Time both.
Solution : you need to convert Date Selected from DateTimePicker control into into Date and Time instead of converting into Date only.
Try This:
dtpTRXdate.Value.ToString("yyyy-MM-dd HH:mm:ss")
Suggestion : by using parameterised queries you do not need to worry about the types being passed as it will be taken care by default.
by using parameterised queries you can avoid SQL Injection Attacks
Complete Code: using parameterised queries
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (_action == "edit")
{
update(_id, int.Parse(cbSupplier.ValueMember), dtpTRXdate.Value, dtpDUEdate.Value, txtRemarks.Text.ToString(), _conn);
}
else
{
insert(int.Parse(cbSupplier.ValueMember), dtpTRXdate.Value, dtpDUEdate.Value, txtRemarks.Text.ToString(), _conn);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void insert(int sup_ID, DateTime TRX_date, DateTime DUE_date, string remarks, MySqlConnection conn)
{
MessageBox.Show(sup_ID.ToString() + " " + TRX_date.ToShortDateSTring() + " " + DUE_date.ToShortDateSTring() + " " + remarks);
MySqlCommand command = new MySqlCommand();
command.Connection = conn;
command.CommandText = "INSERT INTO PO_HEADER VALUES(#value1,#sup_ID,#TRX_date,# DUE_date,#remarks)";
command.Parameters.AddWithValue("#value1",DBNull.Value);
command.Parameters.AddWithValue("#sup_ID",sup_ID);
command.Parameters.AddWithValue("#TRX_date",TRX_date);
command.Parameters.AddWithValue("#DUE_date",DUE_date);
command.Parameters.AddWithValue("#remarks",remarks);
command.ExecuteNonQuery();
}
public void update(int id, int sup_id, string trx_date, string due_date, string remarks, MySqlConnection conn)
{
MySqlCommand command = new MySqlCommand();
command.Connection = conn;
command.CommandText = "UPDATE PO_HEADER SET SUPPLIER_ID=#sup_id,TRX_DATE=#trx_date,DUE_DATE=#due_date,REMARKS=#remarks WHERE ID=#id";
command.Parameters.AddWithValue("#sup_ID",sup_ID);
command.Parameters.AddWithValue("#trx_date",trx_date);
command.Parameters.AddWithValue("#due_date",due_date);
command.Parameters.AddWithValue("#remarks",remarks);
command.Parameters.AddWithValue("#sup_ID",id);
command.ExecuteNonQuery();
}

Exception give msg as :"IndexOutOfRangeException was unhandle OrgerView" in C#, What should I do?

I tried to connect MS Access Db in C# and want to View all.
My Db connection code is show in below
String conStr= #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Administrator\Desktop\SMSGateway2\SMS.mdb;Persist Security Info=True; Jet OLEDB:Database Password=testing" ;
OleDbConnection con;
con = new OleDbConnection(conStr);
string cmdString = "select * from Temp_Order";
OleDbCommand command = new OleDbCommand(cmdString, con);
try
{
con.Open();
command.ExecuteNonQuery();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
richTextBox1.Text = "Student Name: " + reader["SenderNo"].ToString() + "\n" +
"ID: " + reader["OrgerView"].ToString() + "\n" +
"Program: " + reader["OrderTime"].ToString() + "\n" +
"Address: " + reader["Flag"].ToString();
}
}
catch (Exception readexcp)
{
throw readexcp;
}
finally
{
con.Close();
}
First remove this line command.ExecuteNonQuery(); then check SenderNo, OrgerView, OrderTime and Flag are valid column names.

Categories

Resources