I am trying to insert data in Access DB as per selection - c#

Please find attached, my code which i have written, but when it runs and when i enter data in form n click on Submit it gives me error in "Command.executenonquery statement"..
It displays Invalid Operation exception was mishandled
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\databses\electric_data.accdb";
OleDbCommand command = new OleDbCommand();
command.CommandText = "INSERT INTO Electric_Data (Asset_Id,Asset_Name,Emp_Id,Type_of_Asset,Actual_Start_date) VALUES (?,?,?,?,?)";
command.Parameters.Add("#Asset_Id", OleDbType.VarChar, 20).Value = textBox1.Text;
command.Parameters.Add("#Asset_Name", OleDbType.Char, 20).Value = textBox2.Text;
command.Parameters.Add("#Type_of_Asset", OleDbType.VarChar, 20).Value = textBox3.Text;
command.Parameters.Add("#Emp_Id", OleDbType.Char, 20).Value = textBox4.Text;
command.Parameters.Add("#Actual_Start_date", OleDbType.Date).Value = DateTime.Now;
command.ExecuteNonQuery();
conn.Open();
command.Connection = conn;
MessageBox.Show("Entry Registered Successfully.");
}
if (radioButton2.Checked == true)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\databses\electric_data.accdb";
OleDbCommand command = new OleDbCommand();
command.CommandText = "INSERT INTO Electric_Data (Asset_Id,Asset_Name,Emp_Id,Type_of_Asset,Actual_end_date) VALUES (?,?,?,?,?)";
command.Parameters.Add("#Asset_Id", OleDbType.VarChar, 20).Value = textBox1.Text;
command.Parameters.Add("#Asset_Name", OleDbType.Char, 20).Value = textBox2.Text;
command.Parameters.Add("#Emp_Id", OleDbType.VarChar, 20).Value = textBox3.Text;
command.Parameters.Add("#Type_of_Asset", OleDbType.VarChar, 20).Value = textBox4.Text;
command.Parameters.Add("#Actual_end_date", OleDbType.Date).Value = DateTime.Now;
command.ExecuteNonQuery();
conn.Open();
command.Connection = conn;
MessageBox.Show("Entry Registered Successfully.");
}
else if (radioButton1.Checked == false && radioButton2.Checked == false)
MessageBox.Show("Check Work_Start or Work_Complete option for successful Entry.");
}
}
}

You have gotten the conn.Open() in the wrong place. Try -->
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\databses\electric_data.accdb";
OleDbCommand command = new OleDbCommand();
command.CommandText = "INSERT INTO Electric_Data (Asset_Id,Asset_Name,Emp_Id,Type_of_Asset,Actual_Start_date) VALUES (#Asset_Id,#Asset_Name,#Emp_Id,#Type_of_Asset,#Actual_end_date)";
command.Parameters.Add("#Asset_Id", OleDbType.VarChar, 20).Value = textBox1.Text;
command.Parameters.Add("#Asset_Name", OleDbType.Char, 20).Value = textBox2.Text;
command.Parameters.Add("#Emp_Id", OleDbType.VarChar, 20).Value = textBox3.Text;
command.Parameters.Add("#Type_of_Asset", OleDbType.VarChar, 20).Value = textBox4.Text;
command.Parameters.Add("#Actual_end_date", OleDbType.Date).Value = DateTime.Now;
// Open connection and assign to command
conn.Open();
command.Connection = conn;
// Execute non-query command
command.ExecuteNonQuery();
As an aside:
you need to not duplicate conn strings, column names etc in your code. Makes for a nightmare to maintain and debug.
You need to add in try...catch exception handling - what if the DB doesn't open for some reason.
EDIT: command.CommandText as wrong also per answer by other learned people.

Your command text is completely wrong.Change question marks with your parameter names:
command.CommandText = "INSERT INTO Electric_Data (Asset_Id,Asset_Name,Emp_Id,Type_of_Asset,Actual_Start_date) VALUES (#Asset_Id,#Asset_Name,#Emp_Id,#Type_of_Asset,#Actual_end_date)";
You are open your connection after your ExecuteNonQuery, first open your connection,then execute your query
conn.Open();
command.Connection = conn;
command.ExecuteNonQuery();

Try this insert query.Remove ?,?,?,?
command.CommandText = "INSERT INTO Electric_Data (Asset_Id,Asset_Name,Emp_Id,Type_of_Asset,Actual_Start_date) VALUES (#Asset_Id,#Asset_Name,#Emp_Id,#Type_of_Asset,#Actual_end_date)";
check the datatypes of your table-columns

Related

how to insert selected asp.net c# checkbox value to the sql database

i have four check box.but i can not insert selected check box value my SQL table.
my code:-
protected void btnADDSAVE_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=SONU-PC\\SQLEXPRESS; Initial Catalog=Prashant-Online_Store-DB; Integrated Security=true");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_addnewproduct";
cmd.Parameters.Add("#name", SqlDbType.VarChar,50).Value = checkbox.Text.Trim();
cmd.Parameters.Add("#code", SqlDbType.NVarChar, 100).Value = checkbox1.Text.Trim();
cmd.Parameters.Add("#name", SqlDbType.VarChar,50).Value = checkbox3.Text.Trim();
cmd.Parameters.Add("#code", SqlDbType.NVarChar, 100).Value = checkbox4.Text.Trim();
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
Response.Write("Add new product..");
}
catch
{
Response.Write("Not add new product.?");
}
finally
{
con.Close();
con.Dispose();
}
}
As SpiderCode has pointed out, you are trying to get the checkbox text value without checking if the checkbox is checked or not.
use conditional operator to insert the value if checked else insert empty string;
cmd.Parameters.Add("#name", SqlDbType.VarChar,50).Value = checkbox.IsChecked ? checkbox.Text.Trim() : string.Empty;

What query syntax should I use for inserting records in an Oracle database?

I'm a beginner and trying to create a simple program in C# for inserting and updating records in an Oracle database. I have managed to successfully connect to the database but I'm getting an exception for my SQL statement which states that (?) symbol is not supported. Why am I getting this exception and how can I fix this?
My code is:
private void btnSave_Click(object sender, EventArgs e)
{
OracleConnection con = null;
try
{
con = new OracleConnection();
string constr = "Data source=XE; User ID=cloudester; Password=cloudester123;";
if (con.State != ConnectionState.Open)
{
try
{
con.ConnectionString = constr;
con.Open();
//MessageBox.Show("Successfull connection");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception caught");
}
}
if (con.State == ConnectionState.Open)
{
string str = "Insert into EMP_DETAIL(EmpId, Name, Age)";
str += "values (?,?,?)";
OracleCommand cmd = new OracleCommand();
cmd.CommandText = Text;
cmd.Connection = con;
cmd.Parameters.Add(new OracleParameter("EmpId", OracleDbType.Varchar2)).Value = txtEmpId;
cmd.Parameters.Add(new OracleParameter("Name", OracleDbType.Varchar2)).Value = txtName;
cmd.Parameters.Add(new OracleParameter("Age", OracleDbType.Int16)).Value = int.Parse(txtAge.Text);
cmd.ExecuteNonQuery();
}
}
catch { ... }
}
You need to use the named parameter for your command
string str = "Insert into EMP_DETAIL(EmpId, Name, Age) values (:EmpId, :Name, :Age)";
OracleCommand cmd = new OracleCommand();
cmd.CommandText = str; //cmd.CommandText = Text; not sure why did you use Text here
cmd.Connection = con;
cmd.Parameters.Add(new OracleParameter("EmpId", OracleDbType.Varchar2)).Value = txtEmpId;
cmd.Parameters.Add(new OracleParameter("Name", OracleDbType.Varchar2)).Value = txtName;
cmd.Parameters.Add(new OracleParameter("Age", OracleDbType.Int16)).Value = int.Parse(txtAge.Text);
cmd.ExecuteNonQuery();
As agent5566 said, and from OracleCommand.Parameters property;
When using named parameters in an SQL statement called by an
OracleCommand of CommandType.Text, you must precede the parameter name
with a colon (:)
Use them like;
using(var con = new OracleConnection(constr))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"Insert into EMP_DETAIL(EmpId, Name, Age)
values (:EmpId, :Name, :Age)";
cmd.Parameters.Add(new OracleParameter("EmpId", OracleDbType.Varchar2)).Value = txtEmpId;
cmd.Parameters.Add(new OracleParameter("Name", OracleDbType.Varchar2)).Value = txtName;
cmd.Parameters.Add(new OracleParameter("Age", OracleDbType.Int16)).Value = int.Parse(txtAge.Text);
con.Open();
cmd.ExecuteNonQuery();
}
By the way, System.Data.OracleClient has been marked as deprecated in .NET 4 version. You might wanna use Oracle Data Provider for .NET instead.
As an alternative, DataDirect and DevArt also have their own oracle providers for .NET.

Unable to insert data into MS Access database from Visual C#

just a beginner in Programing ...
I use a class to handle the connectionstring .
public class DataBase
{
public OleDbConnection con = new OleDbConnection();
public OleDbCommand cmd = new OleDbCommand();
public void getConnection()
{
con.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Project\Database\DataBase.mdb";
}
private void btnPrint_Click(object sender, EventArgs e)
{
DataBase db = new DataBase();
db.getConnection();
string Name = txtCostumerName.Text;
string DayorNight = cboSwimming.Text;
string Adult1 = txtAdultCount.Text;
string Kid = txtKidsCount.Text;
string Cottage1 = cboCottageType.Text;
string Room = cboRoomType.Text;
string Total1 = lblCottageTotal.Text;
string Cash1 = txtCashRecieve.Text;
string Change1 = txtChange.Text;
db.con.Open();
OleDbCommand command = new OleDbCommand ("INSERT INTO TicketAndCottage (Cotumer_Name , Swimming, Adult, Kids, Cottage, Room , Total, Cash, Change) Values(#Name , #DayorNight , #Adult1 ,#Kid , #Cottage1 , #Room, #Total1 , #Cash1 , #Change1)");
command.Connection = db.con;
command.CommandType = CommandType.Text;
if (db.con.State == ConnectionState.Open)
{
command.Parameters.Add("#Cotumer_Name", OleDbType.VarChar, 20).Value = Name;
command.Parameters.Add("#Swimming", OleDbType.VarChar, 20).Value = DayorNight;
command.Parameters.Add("#Adult", OleDbType.VarChar, 20).Value = Adult1;
command.Parameters.Add("#Kids", OleDbType.VarChar, 20).Value = Kid;
command.Parameters.Add("#Cottage", OleDbType.VarChar, 20).Value = Cottage1;
command.Parameters.Add("#Room", OleDbType.VarChar, 20).Value = Room;
command.Parameters.Add("#Total", OleDbType.VarChar, 20).Value = Total1;
command.Parameters.Add("#Cash", OleDbType.VarChar, 20).Value = Cash1;
command.Parameters.Add("#Change", OleDbType.VarChar, 20).Value = Change1;
try
{
command.ExecuteNonQuery();
MessageBox.Show("Data Added");
db.con.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
//db.con.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
and when i click the button i got "Microsoft JET Database Engine"
Without seeing more context (such as what your connection string and data context look like), I can only take a guess.
One issue appears to be a typo in the field below called "Cotumer_Name". Your text box is named "CostumerName" with an S in there.
OleDbCommand command = new OleDbCommand
("INSERT INTO TicketAndCottage (Cotumer_Name , Swimming, Adult, Kids, Cottage, Room , Total, Cash, Change)
Values(#Name , #DayorNight , #Adult1 ,#Kid , #Cottage1 , #Room, #Total1 , #Cash1 , #Change1)");
It'd be helpful to include some more code.
I figure out whats wrong
private void btnPrint_Click(object sender, EventArgs e)
{
DataBase db = new DataBase();
db.getConnection();
db.con.Open();
string Name = txtCostumerName.Text;
string DayorNight = cboSwimming.Text;
string Adult1 = txtAdultCount.Text;
string Kid = txtKidsCount.Text;
string Cottage1 = cboCottageType.Text;
string Room = cboRoomType.Text;
double Total1 = Convert.ToDouble(lblCottageTotal.Text);
double Cash1 = Convert.ToDouble(txtCashRecieve.Text);
double Change1 = Convert.ToDouble(txtChange.Text);
OleDbCommand command = new OleDbCommand("INSERT INTO TicketAndCottage (Costumer_Name , Swimming, Adult, Kids, Cottage, Room , Total, Cash, Change) Values(#Name , #DayorNight , #Adult1 ,#Kid , #Cottage1 , #Room, #Total1 , #Cash1 , #Change1)", db.con);
if (db.con.State == ConnectionState.Open)
{
command.Parameters.Add("#Costumer_Name", OleDbType.VarChar, 50).Value = Name;
command.Parameters.Add("#Swimming", OleDbType.VarChar, 50).Value = DayorNight;
command.Parameters.Add("#Adult", OleDbType.VarChar, 50).Value = Adult1;
command.Parameters.Add("#Kids", OleDbType.VarChar, 50).Value = Kid;
command.Parameters.Add("#Cottage", OleDbType.VarChar, 50).Value = Cottage1;
command.Parameters.Add("#Room", OleDbType.VarChar, 50).Value = Room;
command.Parameters.Add("#Total", OleDbType.Double, 50).Value = Total1;
command.Parameters.Add("#Cash", OleDbType.Double, 50).Value = Cash1;
command.Parameters.Add("#Change", OleDbType.Double, 50).Value = Change1;
try
{
command.ExecuteNonQuery();
db.con.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
// db.con.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}

i have issue in inserting date in ms access using c#

I m sorry if this question asked before, i am new to c# i am working with ms access database i am storing date to ms access date field...
please check what is the error
My error string is following:
failed to convert parameter value from a string to a timespan
The code is:
private void button1_Click(object sender, EventArgs e)
{
//create connection
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=posv.accdb";
conn.Open();
string Expanse_Name = expanse_name.Text;
string Expanse_Cost = expanse_cost.Text;
string Expanse_Date = expanse_date.Value.ToString("m/d/Y");
OleDbCommand cmd = new OleDbCommand("INSERT INTO expanses (Expanse_Name, Expanse_Cost,Expanse_Date) VALUES (#Expanse_Name, #Expanse_Cost,#Expanse_Date)", conn);
if(conn.State == ConnectionState.Open){
cmd.Parameters.Add("#Expanse_Name", OleDbType.VarChar, 20).Value = Expanse_Name;
cmd.Parameters.Add("#Expanse_Cost", OleDbType.UnsignedInt, 20).Value = Expanse_Cost;
cmd.Parameters.Add("#Expanse_Date", OleDbType.VarChar, 20).Value = Expanse_Date.;
try {
cmd.ExecuteNonQuery();
MessageBox.Show("Expanse Added Success fully!");
}catch(OleDbException exps){
MessageBox.Show(exps.Message);
conn.Close();
} // end try
} //end conn state
} // end save function
You need to specify the right datatype for the db variable. It depends what datatype you've chosen in db. So best approach is look at the respective datatype in the database and change it accordingly.
try this:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=posv.accdb";
conn.Open();
string Expanse_Name = expanse_name.Text;
string Expanse_Cost = expanse_cost.Text;
string Expanse_Date = expanse_date.Value.ToString("m/d/Y");
OleDbCommand cmd = new OleDbCommand("INSERT INTO expanses (Expanse_Name, Expanse_Cost,Expanse_Date) VALUES (#Expanse_Name, #Expanse_Cost,#Expanse_Date)", conn);
if(conn.State == ConnectionState.Open){
cmd.Parameters.Add("#Expanse_Name", OleDbType.VarChar, 20).Value = Expanse_Name;
cmd.Parameters.Add("#Expanse_Cost", OleDbType.UnsignedInt, 20).Value = Expanse_Cost;
cmd.Parameters.Add("#Expanse_Date", OleDbType.DBTimeStamp, 20).Value = Expanse_Date.;
try {
cmd.ExecuteNonQuery();
MessageBox.Show("Expanse Added Success fully!");
}catch(OleDbException exps){
MessageBox.Show(exps.Message);
conn.Close();
} // end try
} //end conn state
}
Change the ToString format on the line line:
string Expanse_Date = expanse_date.Value.ToString("HH:mm:ss.fff");
I think the Expanse_Date should be keep in DateTime and the parameter type for it should be OleDbType.DBTimeStamp. (And please use using blocks.)
private void button1_Click(object sender, EventArgs e)
{
using (var conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=posv.accdb"))
{
conn.Open();
var Expanse_Name = expanse_name.Text;
var Expanse_Cost = expanse_cost.Text;
var Expanse_Date = expanse_date.Value;
using (var cmd = new OleDbCommand("INSERT INTO expanses (Expanse_Name, Expanse_Cost,Expanse_Date) VALUES (#Expanse_Name, #Expanse_Cost,#Expanse_Date)", conn))
{
cmd.Parameters.Add("#Expanse_Name", OleDbType.VarChar, 20).Value = Expanse_Name;
cmd.Parameters.Add("#Expanse_Cost", OleDbType.UnsignedInt, 20).Value = Expanse_Cost;
cmd.Parameters.Add("#Expanse_Date", OleDbType.DBTimeStamp, 20).Value = Expanse_Date;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Expanse Added Success fully!");
}
catch (OleDbException exps)
{
MessageBox.Show(exps.Message);
conn.Close();
}
}
}
}

Error while executing a sql command in c#

I am using asp.net with c# and there exist an error in these line of codes.
protected void btnsubmit_Click(object sender, EventArgs e)
{
string type = "c";
string FID = Session["FID"].ToString();
SqlConnection cn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
//int str_diff = Convert.ToInt32(ConfigurationManager.AppSettings["Difference"]);
cn.ConnectionString = #"Data Source=BOPSERVER;Initial Catalog=Project;Integrated Security=True";
cn.Open();
cmd.CommandText = "update TrackingFaculty_det SET Type=#Type WHERE (FID=#FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60";
cmd.Parameters.Add("#FID",SqlDbType.VarChar,10);
cmd.Parameters["#FID"].Value = FID;
cmd.Parameters.Add("#Type", SqlDbType.VarChar, 1);
cmd.Parameters["#Type"].Value = type;
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect("~/Faculty/Personaldet.aspx");
}
You haven't set the connection to the command
cmd.Connection = cn;
You need to assign the SqlConnection to the SqlCommand. As an additional suggestion I would wrap the connection in a using block to ensure it is correctly disposed in the case of an exception.
using (SqlConnection cn = new SqlConnection(#"Data Source=BOPSERVER;Initial Catalog=Project;Integrated Security=True")
{
cn.Open();
SqlCommand cmd = new SqlCommand("update TrackingFaculty_det SET Type=#Type WHERE (FID=#FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60", cn);
cmd.Parameters.Add("#FID",SqlDbType.VarChar,10);
cmd.Parameters["#FID"].Value = FID;
cmd.Parameters.Add("#Type", SqlDbType.VarChar, 1);
cmd.Parameters["#Type"].Value = type;
cmd.ExecuteNonQuery();
}
SqlCommand cmd = new SqlCommand("update TrackingFaculty_det SET Type=#Type WHERE (FID=#FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60", cn);
cmd.Parameters.Add("#FID",SqlDbType.VarChar,10);
cmd.Parameters["#FID"].Value = FID;
cmd.Parameters.Add("#Type", SqlDbType.VarChar, 1);
cmd.Parameters["#Type"].Value = type;
cmd.ExecuteNonQuery();

Categories