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();
}
}
}
}
Related
I have a FileUpload control and when I don't insert an image, I want to insert DBNull into the database. So far I have only errors with DBNull.Value. The table allow null for column ImageData.
Here is the code:
protected void button_sign_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == true)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/userimage/" + str));
string Image = "~/userimage/" + str.ToString();
string name = username_textbox.Text;
string email = email_textbox.Text;
string pass = password_textbox.Text;
string CS = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("insert into Register values(#Username, #Email, #Password, #ImageData)", con);
cmd.Parameters.AddWithValue("#Username", name);
cmd.Parameters.AddWithValue("#Email", email);
cmd.Parameters.AddWithValue("#Password", pass);
cmd.Parameters.AddWithValue("#ImageData", Image);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
lblMsg.Text = "Înregistrare cu succes";
Response.AddHeader("REFRESH", "2;URL=login.aspx");
}
}
else
{
lblMsg.Text = "Error";
}
}
This should be enough
cmd.Parameters.AddWithValue("#ImageData", FileUpload1.HasFile ? Image: DbNull.Value);
Also refactor your code a little bit:
string image = "";
if (FileUpload1.HasFile==true)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/userimage/" + str));
image = "~/userimage/" + str.ToString();
}
string name = username_textbox.Text;
string email = email_textbox.Text;
string pass = password_textbox.Text;
String connString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection con = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("insert into Register values(#Username,#Email,#Password,#ImageData)", con);
cmd.Parameters.AddWithValue("#Username", name);
cmd.Parameters.AddWithValue("#Email", email);
cmd.Parameters.AddWithValue("#Password", pass);
cmd.Parameters.AddWithValue("#ImageData", FileUpload1.HasFile ? image: DbNull.Value);
con.Open();
cmd.ExecuteNonQuery();
}
lblMsg.Text = "Înregistrare cu succes";
Response.AddHeader("REFRESH", "2;URL=login.aspx");
Don't start your variables with UpperCase letters.
If you set the value of Image at the beginning the rest of the code could stay generic.
protected void button_sign_Click(object sender, EventArgs e)
{
object Image;
if (FileUpload1.HasFile==true)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/userimage/" + str));
Image = "~/userimage/" + str.ToString();
}
else {
Image = System.DBNull.Value;
}
string name = username_textbox.Text;
string email = email_textbox.Text;
string pass = password_textbox.Text;
String CS = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
using(SqlCommand cmd = new SqlCommand("insert into Register values(#Username,#Email,#Password,#ImageData)", con))
{
// pick the appropriate SqlDbType type for each parameter
cmd.Parameters.Add(new SqlParameter("#Username", SqlDbType.VarChar){Value = name});
cmd.Parameters.Add(new SqlParameter("#Email", SqlDbType.VarChar){Value = email});
cmd.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar){Value = pass});
cmd.Parameters.Add(new SqlParameter("#ImageData", SqlDbType.VarChar){Value = Image});
con.Open();
cmd.ExecuteNonQuery();
lblMsg.Text = "Înregistrare cu succes";
Response.AddHeader("REFRESH", "2;URL=login.aspx");
}
Some other notes though
You should specify the Database types using the SqlDbType in your parameters to make sure that the values are translated correctly by the ado.net code.
Wrap you Command in a using block as well
No need to close the connection, the using block will handle that for you.
Do not store passwords in clear text. Instead store a salted hash of the password.
I'm using OleDbDataAdapter class to get data from an Access (.mdb) file.
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+Environment.CurrentDirectory+"\\Data.mdb;Jet OLEDB:Database Password=pass");
OleDbCommand com = new OleDbCommand(query, con);
DataTable dt = new DataTable();
con.Open();
OleDbDataAdapter oda = new OleDbDataAdapter(com);
oda.Fill(dt);
oda.Dispose();
com.Parameters.Clear();
con.Close();
return dt;
The problem is that by debugging I found out, oda.Fill(dt) takes a very long time to execute. (around 10 seconds)
I have 50,000 records in the database and I only need to retrieve 1 row.
Please help. Thank you in advance.
If all you need is one row try using a data reader as shown below, of your you will need to adjust pieces like database name, field list etc.
Note I write output to the IDE Output window so have it open when trying this with your code/data.
public partial class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
int id = 0;
if (int.TryParse(textBox1.Text, out id))
{
OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder();
Builder.Provider = "Microsoft.Jet.OLEDB.4.0";
Builder.DataSource = Path.Combine(Application.StartupPath, "Database1.mdb");
using (OleDbConnection cn = new OleDbConnection(Builder.ConnectionString))
{
string selectStatement = "SELECT UserName, JoinMonth FROM Users WHERE Identifier = #Identifier";
using (OleDbCommand cmd = new OleDbCommand { CommandText = selectStatement, Connection = cn })
{
cmd.Parameters.Add(new OleDbParameter { ParameterName = "#Identifier", DbType = DbType.Int32, Value = id });
cn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
Console.WriteLine("{0} - {1}", dr.GetString(0), dr.GetString(1));
}
else
{
Console.WriteLine("Not located");
}
}
}
}
}
}
If I enter a value(already entered in DB) and click a button(Retrieve) in my windows form, I have to retrieve date and time to my datetimepicker1 from SQL(already entered values).
Please correct my code.
This is my code.
private void button9_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=NIFAL;Initial Catalog=LaundrySystem;Integrated Security=True;");
con.Open();
str = "select * from LaundrySystemTable where laundID='" + textBox1.Text.Trim() + "'";
cmd = new SqlCommand(str, con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
string temp1 = reader["entryDate"].ToString();
DateTime dt1 = DateTime.Parse(temp1);
dateTimePicker1.Value = dt1.ToString("MM:dd:yyyy");
reader.Close();
con.Close();
}
}
NEVER use such an SQL that is open to SQL inkjection attacks, use parameters instead:
using (SqlConnection con = new SqlConnection("Data Source=NIFAL;Initial Catalog=LaundrySystem;Integrated Security=True;"))
{
string sql = "select entryDate from LaundrySystemTable where laundID=#id";
var cmd = new SqlCommand( sql, con );
cmd.Parameters.AddWithValue( "#id", textBox1.Text.Trim() ); // if its type is not string, then do the conversion here
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
dateTimePicker1.Value = (DateTime?)reader["entryDate"];
}
con.Close();
}
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
I create a web form that contains: Dropdownlist, texbox and rename button.
The general idea is that Dropdownlist contains list of column names of one table in my database.
Then the user select one of these names and enter the new name in the textbox. After that, he click the rename button. The result is rename the selected column in my database.
My code is work well. And it is give exact result.
see my code:
protected void Button1_Click(object sender, EventArgs e)
{
string conString = #"Data Source=FATTO-TOSH\SQLEXPRESS;Initial Catalog=Positions;Integrated Security=True";
if (DropDownList1.SelectedIndex == 0)
using (var con = new SqlConnection(conString))
{
var cmd = new SqlCommand("sys.sp_rename", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname", "PositionsReq.skill1")
.SqlDbType = SqlDbType.NVarChar;
cmd.Parameters.AddWithValue("#newname", name.Text)
.SqlDbType = SqlDbType.NVarChar;
cmd.ExecuteNonQuery();
}
if (DropDownList1.SelectedIndex == 1)
using (var con = new SqlConnection(conString))
{
var cmd = new SqlCommand("sys.sp_rename", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname", "PositionsReq.skill2")
.SqlDbType = SqlDbType.NVarChar;
cmd.Parameters.AddWithValue("#newname", name.Text)
.SqlDbType = SqlDbType.NVarChar;
cmd.ExecuteNonQuery();
}
if (DropDownList1.SelectedIndex == 2)
using (var con = new SqlConnection(conString))
{
var cmd = new SqlCommand("sys.sp_rename", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname", "PositionsReq.skill3")
.SqlDbType = SqlDbType.NVarChar;
cmd.Parameters.AddWithValue("#newname", name.Text)
.SqlDbType = SqlDbType.NVarChar;
cmd.ExecuteNonQuery();
}
}
My question is:
The modification achieved only one time (regard to one column) because when I change the name from skill1 to Sk for example. May in other time, the user want to modify Sk to other name. the code doesn't work because it is initialize as column name is skill1 only. do you have an idea how to generalize the code to work whatever the name of the column?
thank you
Instead of using DropDownList1.SelectedIndex why don't you have the name of the column you want it to be changed to listed in the DropDownList1 and then use DropDownList1.SelectedValue like so:
protected void Button1_Click(object sender, EventArgs e)
{
string conString = #"Data Source=FATTO-TOSH\SQLEXPRESS;Initial Catalog=Positions;Integrated Security=True";
using (var con = new SqlConnection(conString))
{
var cmd = new SqlCommand("sys.sp_rename", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#objname", DropDownList1.SelectedValue)
.SqlDbType = SqlDbType.NVarChar;
cmd.Parameters.AddWithValue("#newname", name.Text)
.SqlDbType = SqlDbType.NVarChar;
cmd.ExecuteNonQuery();
}
}
MSDN
Make sure you toss in some null checking on the SelectedValue before you actually execute any commands.