Issues with the insert function to my database program - c#

Good day all! I'm having a minor issue with the insert to my program. See, the code has no errors but I'm having an OleDb exception when trying to insert. The other parts of my project work fine but there is a tiny issue here that I can't seem to find
public void Insert()
{
//myDb = new OleDbConnection(conn + dbFile);
myDb.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Employee", myDb);
//
OleDbCommand cmd = new OleDbCommand("INSERT INTO Employee(Username, Password, email, phone) VALUES ('" + insUn + "','" + insPass + "','" + insNm + "','" + insNmr + "')", myDb);
adapter.InsertCommand = cmd;
adapter.InsertCommand.ExecuteNonQuery();
DataSet ds = new DataSet();
adapter.Fill(ds, "Employee");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Employee";
myDb.Close();
}
The other functions such as the search and delete work but I can't find the problem here
These are the exceptions:
try
{
if (textBox2.Text != "")
{
insUn = textBox2.Text;
insNmr = textBox4.Text;
insPass = textBox3.Text;
insNm = textBox5.Text;
}
Insert();
}
catch (OleDbException ex)
{
MessageBox.Show("Error, please try again", "Exception", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
}
catch (FormatException ex)
{
MessageBox.Show("One or more fields have not been entered. Please check and re-enter", "Missing fields", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
enter code here

Abdellah's answer will work, but be aware for SQL Injection attacks when building your query string. You should build it like this:
OleDbCommand cmd = new OleDbCommand("INSERT INTO Employee(Username, Password, email, phone) VALUES (#p1, #p2, #p3, #p4)", myDb);
int maxSize = 50;
cmd.Paramters.Add("#p1", SqlDbType.VarChar, maxSize).Value = insUn;
cmd.Parameters.Add("#p2", SqlDbType.VarChar, maxSize).Value = insPass;
cmd.Parameters.Add("#p3", SqlDbType.VarChar, maxSize).Value = insNm;
cmd.Parameters.Add("#p4", SqlDbType.VarChar, maxSize).Value = insNmr;

I advice you to use the Parameter to avoid SQL injections , and put the brackets [] in query for [Password] because it's a keyword like below :
public void Insert()
{
//myDb = new OleDbConnection(conn + dbFile);
myDb.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO Employee(Username, [Password], email, phone) VALUES (#Username, #Password, #email, #phone)", myDb);
cmd.Parameters.AddWithValue("#Username", insUn);
cmd.Parameters.AddWithValue("#Password", insPass);
cmd.Parameters.AddWithValue("#email", insNm);
cmd.Parameters.AddWithValue("#phone", insNmr);
cmd.ExecuteNonQuery();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Employee", myDb);
DataSet ds = new DataSet();
adapter.Fill(ds, "Employee");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Employee";
myDb.Close();
}

Related

C# Display data based on userID

Hi I'm creating a C# program where users can login and book bus seats for destinations, I have the program so users can insert/update/delete data but I want the data to just display the currently logged-in data, this is my code below.
This function is in the main dashboard class where it displays the seats table to the dataviewgrid
private void displayBookings()
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from seats";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
This is my database table and all I want to do once a user is logged in is display each seatID by the userID, the seatid is the primary key for this table and the userid is a foreign key linked to the userdata table.
EDIT:
private void displayBookings()
{
SqlConnection con = new SqlConnection(#"CONNECTIONSTRING");
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from seats WHERE userID = #userID";
//add the user id as a parameter
SqlParameter p_userID = new SqlParameter("#userID", SqlDbType.Int);
// the userID of the logged in user
p_userID.Value = cmd.Parameters.Add(p_userID);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Login method
private void loginButton_Click(object sender, EventArgs e)
{
StringBuilder errorMessages = new StringBuilder();
using (SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Brandon Brock\source\repos\SE2\Booking System\Database1.mdf;Integrated Security=True"))
{
con.Open();
string str1 = "select * from userdata where username='" + log_username.Text + "' and password_1='" + log_password.Text + "'";
SqlCommand cmd = new SqlCommand(str1, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(str1, con);
da.SelectCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 1)
{
switch (dt.Rows[0]["type"] as string)
{
case "admin":
{
MessageBox.Show("You are logged in!", "Admin Portal", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Hide();
new Admin().Show();
break;
}
case "user":
{
MessageBox.Show("You are logged in!", "Seat Reservation", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Hide();
new Dashboard().Show();
break;
}
default:
{
MessageBox.Show("Enter Correct Username and Password");
break;
}
}
log_username.Text = "";
log_password.Text = "";
}
else
{
MessageBox.Show("Username or Password is wrong or Account doesn't exist!", "Bus Seat Account Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (SqlException ex)
{
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
Console.WriteLine(errorMessages.ToString());
}
}
}
Assuming you have access to the logged in user data:
con.Open(); // <-- can't see where this comes from but is almost certainly an anti-pattern. Don't re-use SqlConnection instances, make new ones and Dispose() when done.
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from seats WHERE userID = #userID";
//add the user id as a parameter
SqlParameter p_userID = new SqlParameter("#userID", SqlDbType.Int);
p_userID.Value = // the userID of the logged in user
cmd.Parameters.Add(p_userID);
//cmd.ExecuteNonQuery(); <-- this is pointless, delete it
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();

How to post records from my windows form to my database

Good day, thanks for the assistance previously. please am trying to POST records from my window form to database, am having challenges with it, how do i do it?
Below is the code snippet i coded it with
private void btnNext_Click(object sender, EventArgs e)
{
//Calling Window Work experience page
WorkExperience frm = new WorkExperience();
frm.ShowDialog();
string connectionString = #"Data Source=localhost;" +
"Initial Catalog=EmploymentDb;Integrated Security=true; User Instance=False";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.Connection = connection;
//command.CommandText
string sql = "INSERT INTO EmploymentDb " +
"(Id,Title, LastName, FirstName, MiddleName, Gender, Address, Email, City, State, MobileNumber, DateOfBirth, HomePhone, DistchargeCertNumber, SchoolAttended, NYSCStatus, AgeLimit) VALUES " +
"(#Id, #Title, #LastName, #FirstName, #MiddleName, #Gender, #Address, #Email, #City, #State, #MobileNumber, #DateOfBirth, #HomePhone, #DistchargeCertNumber, #SchoolAttended, #NYSCStatus, #AgeLimit)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Id", txtID.Text);
cmd.Parameters.AddWithValue("#Title", comboBoxtTitle.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#MiddleName", txtMiddleName.Text);
cmd.Parameters.AddWithValue("#Gender", comboBoxGender.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#City", comboBoxCity.Text);
cmd.Parameters.AddWithValue("#State", comboBoxState.Text);
cmd.Parameters.AddWithValue("#MobileNumber", txtMobileNo.Text);
cmd.Parameters.AddWithValue("#DateOfBirth", dateTimePickerDOB.Text);
cmd.Parameters.AddWithValue("#HomePhone", txtHomePhone.Text);
cmd.Parameters.AddWithValue("#DistchargeCertNumber", txtNYSCCertNumder.Text);
cmd.Parameters.AddWithValue("#SchoolAttended", txtSchoolAttended.Text);
cmd.Parameters.AddWithValue("#NYSCStatus", comboBoxNYSCStatus.Text);
cmd.Parameters.AddWithValue("#AgeLimit", cbxAgeLimit.Text);
int affectedRows = cmd.ExecuteNonQuery();
MessageBox.Show(affectedRows + "Row inserted!");
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds, "Employment");
FillControls();
btnNext.Enabled = true;
// btnPrevious.Enabled = true;
}
You need to provide SqlConnection for SqlDataAdapter, if you want to retrieve the data back. Otherwise, you can delete the following 4 lines of code.
var query = "SELECT Id,Title FROM EmploymentDb";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
^^^^^^
DataSet ds = new DataSet();
da.Fill(ds, "Employment");

How to upload to Database SQL Server? where is the possible coding error?

string fname=""; <----- Global variable
HtmlInputFile file = (HtmlInputFile)place.FindControl("f_upload");
if (filename.Value.Equals(""))
{
span1.InnerHtml = "<b>Error Message : A File Name must be enter </b>";
return;
}
if (file.PostedFile.ContentLength > 0)
{
try
{
file.PostedFile.SaveAs("c:\\WADUploadFile\\" + filename.Value);
fname = "c:\\WADUploadFile\\" + filename.Value;
//checking fname value
Response.Write(fname);
span1.InnerHtml = "File is uploaded successfully to" + "<b>C:\\WADUploadFile\\" +
filename.Value + "</b>at the server";
}
catch (Exception exc)
{
span1.InnerHtml = "Error occured while saving file to" +
"<b>c:\\WADUploadFile\\" + filename.Value + "</b><br/>" + "[ " +
exc.ToString() + " ]";
}
}
string sql1 = "INSERT INTO Thread (Th_id, Th_poster, Th_date) VALUES (#id, #poster, #date)";
string sql2 = "INSERT INTO ThreadCommend(C_id,C_content,C_upload,T_id,Th_id)Values(#Cid,#Ccontent,#Cupload,#Tid,#Thid)";
con.Open();
SqlCommand cmd1 = new SqlCommand(sql1, con);
cmd1.Parameters.AddWithValue("#id", threadId);
cmd1.Parameters.AddWithValue("#poster", tempPoster);
cmd1.Parameters.AddWithValue("#date", DateTime.Now);
SqlCommand cmd2 = new SqlCommand(sql2, con);
cmd2.Parameters.AddWithValue("#Cid", commendId);
cmd2.Parameters.AddWithValue("#Ccontent", txt);
cmd2.Parameters.AddWithValue("#Cupload", fname.ToString());
cmd2.Parameters.AddWithValue("#Tid", topicId);
cmd2.Parameters.AddWithValue("#Thid", threadId);
//SqlDataAdapter daInsert = new SqlDataAdapter();
//daInsert.InsertCommand = cmdInsertDesc.ToString();
int x = cmd1.ExecuteNonQuery();
con.Close();
con.Open();
int y = cmd2.ExecuteNonQuery(); <--- Error appear here
string note = "Topic added sucussfully";
if (x > 0)
{
Response.Write(note.ToString());
//Response.Write(x.ToString());
}
if (y > 0)
{
Response.Write(note.ToString());
//Response.Write(x.ToString());
}
con.Close();
My question is: how do I upload to the SQL Server database? Is it a problem to ExecuteNonQuery 2 times with each different object?
The error message:
SqlException was unhandled by user code
The parameterized query '(#Cid int,#Ccontent nvarchat(6),#Cupload
nvarchar(4000),#Tid int expects the parameter '#Cupload' which was not
supplied.
What is wrong with my code that I can't add add data to database? T.T
This is an old thread and Im sure you found a fix but it looks like you could have an injection problem. try giving the sqlcommand a data type for each parameter using a SqlDataAdapter.
not sure what your data types are but it should look something like this. Also utilize the using statement so you don't have to close/dispose the connections
using (con)
{
con.Open();
SqlDataAdapter cmd1 = new SqlDataAdapter();
cmd1 = new SqlCommand(sql1, con);
cmd1.InsertCommand.Parameters.Add("#id", SqlDbType.Int).Value = threadId;
cmd1.InsertCommand.Parameters.Add("#poster", SqlDbType.NVarChar).Value = tempPoster;
cmd1.InsertCommand.ExecuteNonQuery();
SqlDataAdapter cmd2 = new SqlDataAdapter();
cmd2 = new SqlCommand(sql2, con);
cmd2.InsertCommand.Parameters.Add("#Cid", SqlDbType.Int).Value = commendId;
cmd2.InsertCommand.Parameters.Add("#Ccontent", SqlDbType.Nvarchar).Value = txt;
cmd2.InsertCommand.Parameters.Add("#Cupload", SqlDbType.Nvarchar).Value = fname.ToString();
cmd2.InsertCommand.Parameters.Add("#Tid", SqlDbType.Int).Value = topicId;
cmd2.InsertCommand.Parameters.Add("#Thid", SqlDbType.Int).Value = threadId;
cmd2.InsertCommand.ExecuteNonQuery();
}

Link Dataset with SQL server : Fail

I've literally searched everything and everywhere but somehow this piece of code of mine just won't work no matter what I've tried.
So I have created a database on a SQL server and linked it, tested it, great it works. OK, so the problem is when I'm trying to insert data on a website textbox and have THAT data copied/transferred into my database table. So I only now get an error saying that 'Exception unhandeld and Must declare the scalar variable "#f_name".
I would appreciate it if anyone can assist? Thanks.
private void Save(string hfname, string hlname, string hemail, string hcomment)
{
SqlConnection myConn = new SqlConnection(GetConnectionString());
String sql = "INSERT INTO helpdesk (First_Name, Last_Name, Email, Comments) VALUES " + " (#f_name, #l_name, #email, #comment)";
SqlCommand cmd = new SqlCommand(sql, myConn);
ITDBDataset itdbDataSet = new ITDBDataset();
SqlDataAdapter dataAdapter;
try
{
myConn.Open();
dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(itdbDataSet);
myConn.Close();
SqlParameter[] param = new SqlParameter[6];
//para,[0]
param[0] = new SqlParameter("#f_name", System.Data.SqlDbType.VarChar, 50);
param[1] = new SqlParameter("#l_name", System.Data.SqlDbType.VarChar, 50);
param[2] = new SqlParameter("#email", System.Data.SqlDbType.VarChar, 30);
param[3] = new SqlParameter("#comment", System.Data.SqlDbType.VarChar, 600);
param[0].Value = hfname;
param[1].Value = hlname;
param[2].Value = hemail;
param[3].Value = hcomment;
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
//SqlDataReader reader = cmd.ExecuteReader();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Not Added, check context!";
msg += ex.Message;
throw new Exception(msg);
}
//finally
//{
// myConn.Close();
//}
}
Any suggestions to what could have gone wrong?
You have forgotten to add the parameters to your command and you close the connection before the call of the method. I propose you using:
private void Save(string hfname, string hlname, string hemail, string hcomment)
{
SqlConnection myConn = new SqlConnection(GetConnectionString());
String sql = "INSERT INTO helpdesk (First_Name, Last_Name, Email, Comments) VALUES " + " (#f_name, #l_name, #email, #comment)";
SqlCommand cmd = new SqlCommand(sql, myConn);
ITDBDataset itdbDataSet = new ITDBDataset();
SqlDataAdapter dataAdapter;
try
{
myConn.Open();
dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(itdbDataSet);
SqlParameter[] param = new SqlParameter[6];
//para,[0]
param[0] = new SqlParameter("#f_name", System.Data.SqlDbType.VarChar, 50);
param[1] = new SqlParameter("#l_name", System.Data.SqlDbType.VarChar, 50);
param[2] = new SqlParameter("#email", System.Data.SqlDbType.VarChar, 30);
param[3] = new SqlParameter("#comment", System.Data.SqlDbType.VarChar, 600);
param[0].Value = hfname;
param[1].Value = hlname;
param[2].Value = hemail;
param[3].Value = hcomment;
cmd.Parameters.AddRange(param);//add the parameters
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
//SqlDataReader reader = cmd.ExecuteReader();
myConn.Close();
}
I suggest you use AddWithValue eg
SqlConnection myConn = new SqlConnection(GetConnectionString());
String sql =
"INSERT INTO helpdesk (First_Name, Last_Name, Email, Comments) VALUES " +
" (#f_name, #l_name, #email, #comment)";
SqlCommand cmd = new SqlCommand(sql, myConn);
cmd.Parameters.AddWithValue("#f_name",hfname);
cmd.Parameters.AddWithValue("#l_name",hlname);
cmd.Parameters.AddWithValue("#email",hemail);
cmd.Parameters.AddWithValue("#comment",hcomment);
ITDBDataset itdbDataSet = new ITDBDataset();
SqlDataAdapter dataAdapter;
try
{
myConn.Open();
dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(itdbDataSet);
myConn.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Not Added, check context!";
msg += ex.Message;
throw new Exception(msg);
}

How do I go about adding records into TWO tables into Access Database?

I am a new member. Also, I am trying to add a record into 2 different tables (customerinfo & studentinfo). My code is below but it only records the textbox fields into the StudentInfo Table only. How should I go about it putting the record into 2 tables simultaneously?
Thanks
protected void btnRegister_Click(object sender, EventArgs e)
{
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data source="
+ Server.MapPath("~/App_Data/webBase.accdb");
mDB.Open();
Type csType = this.GetType();
//check to ensure that UserId keyed in is not being used by other Customers
OleDbCommand cmd;
OleDbCommand cmd1;
OleDbDataReader rdr;
OleDbDataReader rdr1;
string strSQLSelect = "SELECT sUserId FROM studentInfo ORDER BY sUserId";
string strSQLSelect1 = "SELECT cUserId FROM customerInfo ORDER BY cUserId";
cmd1 = new OleDbCommand(strSQLSelect1, mDB);
cmd = new OleDbCommand(strSQLSelect, mDB);
rdr = cmd.ExecuteReader();
rdr1 = cmd1.ExecuteReader();
this.txtPassword.Attributes.Add("value", this.txtPassword.Text);
// insert new record
string strSQLInsert = "INSERT INTO "
+ "studentInfo (sUserId,sPassword,sName,sAddress,sTel,sEmail,sLevel, sLevel2)"
+ "VALUES(#uid,#pw,#name,#addr,#em,#tel,#lvl,#lvl2)";
ClientScript.RegisterStartupScript(csType, "Successful!", scriptSuccessNewAccount);
cmd = new OleDbCommand(strSQLInsert, mDB);
cmd.Parameters.AddWithValue("#uid", txtUserId.Text);
cmd.Parameters.AddWithValue("#pw", txtPassword.Text);
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#addr", txtAddress.Text);
cmd.Parameters.AddWithValue("#em", txtEmail.Text);
cmd.Parameters.AddWithValue("#tel", txtTel.Text);
cmd.Parameters.AddWithValue("#lvl", DropDownList1.Text);
cmd.Parameters.AddWithValue("#lvl2", DropDownList2.Text);
string strSQLInsert1 = "INSERT INTO "
+ "customerInfo (cUserId,cPassword,cName,cAddress,cEmail,cTel,cCountry)"
+ "VALUES(#uid,#pw,#name,#addr,#em,#tel,#country)";
ClientScript.RegisterStartupScript(csType, "Successful!", scriptSuccessNewAccount);
cmd1 = new OleDbCommand(strSQLInsert1, mDB);
cmd1.Parameters.AddWithValue("#uid", txtUserId.Text);
cmd1.Parameters.AddWithValue("#pw", txtPassword.Text);
cmd1.Parameters.AddWithValue("#name", txtName.Text);
cmd1.Parameters.AddWithValue("#addr", txtAddress.Text);
cmd1.Parameters.AddWithValue("#em", txtEmail.Text);
cmd1.Parameters.AddWithValue("#tel", txtTel.Text);
cmd1.Parameters.AddWithValue("#country", txtCountry.Text);
cmd.ExecuteNonQuery();
mDB.Close();
It looks like you're missing
cmd1.ExecuteNonQuery()
for the other table.

Categories