I have a text box that is filled with date(date type) from a date picker.
I have a table with 3 columns(name,fromdate(date),todate(date)). On button click activity it should show only those names which have the date specified between the from date and to date.
I would like some help me on this
string v = System.Configuration.ConfigurationManager.ConnectionStrings["harish"].ConnectionString;
con = new OracleConnection(v);
con.Open();
cmd = new OracleCommand("________", con);
You're not even trying. Try Oracle and MSDN for this.
But since you're in a jam....
var cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Table (name, fromDate, toDate)VALUES(:nameVal, :fromVal, :toVal)";
cmd.Parameters.Add(new OracleParameter(":fromVal", OracleType.DateTime)).Value = fromDateVal;
cmd.Parameters.Add(new OracleParameter(":toVal", OracleType.DateTime)).Value = toDateVal;
cmd.ExecuteNonQuery();
//close the connection after done.... release the resources
Related
The problem is am getting an exception error that says data mismatch in the external database when i try to insert
I have a customer booking table with booking id ...pk as auto number, customer.... fk and date in as datetime
Booking id is auto increment so i don't need to insert anything
What i want to achieve is to insert into customer_id and date in thats all but i keep getting the data mismatch and number of query valuesis not the same as destination fields
So what is the right way to put this
using (OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString())) {
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into customer_booking ([customer_id],[date_in]) values (?,?)";
cmd.Parameters.AddWithValue("#customer_id", txtusername.Text);
cmd.Parameters.AddWithValue("#date_in", dtdate_in);
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("your booking was successful ", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
use cmd.Parameters.add('...') method as follow :
using (OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString())) {
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into customer_booking ([customer_id],[date_in]) values (#customer_id,#date_in)";
///* Set your column dataType*/
cmd.Parameters.Add("#customer_id", SqlDbType.VarChar , 50).Value = txtusername.Text;
cmd.Parameters.Add("#date_in", SqlDbType.DateTime).Value = dtdate_in;
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("your booking was successful ", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
I am trying to select then insert a datetime from Table 1 to Table 2. I have successfully insert the data. However, the datetime shown in Table 2 is 0000-00-00 00:00:00. Idk where is the error. Someone please help me with this problem. I am struggling with this. And is this the correct way to SELECT then insert ? (Select from Table 1 then INSERT into Table 2)
try
{
string myConnectionString;
myConnectionString= "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
EncodingProvider ppp;
ppp = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp);
connection.Open();
string select = "Select time from assign where userId=#name";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.CommandText = select;
cmd.Connection = connection;
MySqlDataReader selectAssign = cmd.ExecuteReader();
selectAssign.Read();
string assign = (selectAssign["time"].ToString());
selectAssign.Close();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into bluetooth (userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name, #stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assign);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.Connection = connection;
cmd.ExecuteNonQuery();
connection.Close();
}
catch (MySqlException ex)
{
txtExercise.Text = ex.ToString();
}
Please try with this
try
{
string myConnectionString;
myConnectionString = "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection = new
MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
EncodingProvider ppp;
ppp = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp);
connection.Open();
string select = "Select time from assign where userId=#name";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.CommandText = select;
cmd.Connection = connection;
MySqlDataReader selectAssign = cmd.ExecuteReader();
selectAssign.Read();
string assign = (selectAssign["time"].ToString());
selectAssign.Close();
DateTime assignDate = DateTime.Now;
DateTime.TryParseExact(assign, out assignDate);
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into bluetooth
(userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name,
#stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assignDate);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.Connection = connection;
cmd.ExecuteNonQuery();
connection.Close();
}
catch (MySqlException ex)
{
txtExercise.Text = ex.ToString();
}
}
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
cmd.Parameters.AddWithValue("#stupid4", GetDateString(assign));
Have a method like this:
public static string GetDateString(string date)
{
DateTime theDate;
if (DateTime.TryParseExact(date, "dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out theDate))
{
// the string was successfully parsed into theDate
return theDate.ToString("dd/MM/yyyy HH:mm:ss");
}
else
{
// the parsing failed, return some sensible default value
return string.Empty;
}
}
You need to use .ExecuteReader() the use .Read() to move to each row in the result set. If you are sure the exactly one row will be returned, use .ExecuteScalar() instead. Research on the difference of both online. Below is an example using .ExecuteReader().
I also re-wrote to use using statements to simplify a bit but not deviate too much from your original code so you do not need to worry about closing and disposing resources since they inherit from IDisposable and will do that automatically once they exit the using block:
string assign = DateTime.Now.ToString();
string myConnectionString;
myConnectionString= "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
string select = "Select time from assign where userId=#name";
using (MySqlConnection con = new MySqlConnection(myConnectionString))
{
using (MySqlCommand cmd = new MySqlCommand(select))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#name", txtValue.Text);
using (MySqlDataReader cursor = cmd.ExecuteReader())
{
while (cursor.Read())
{
assign = cursor["time"];
}
}
}
string insert = "INSERT into bluetooth (userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name, #stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
using (MySqlCommand cmd = new MySqlCommand(insert))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assign);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.ExecuteNonQuery();
}
}
So I have a form that when it is opened, loads selected information from a database. However, I want to truncate the Date column, so instead of showing how
'DD/MM/YYYY HH:mm:ss a.m/p.m'
I want it to only show
'DD/MM/YYYY'
I'm using SQL Server Management Studio for my database, and was under the impression that a Date type in that didn't record the time field anyway.
My code for populating the DGV:
SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=FarmersMarket;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
cmd.Connection = con;
con.Open();
cmd.CommandText = "Select EventID, EventDate, Location from Events";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
int n = dgvEvents.Rows.Add();
dgvEvents.Rows[n].Cells[0].Value = dr[0].ToString();
dgvEvents.Rows[n].Cells[1].Value = dr[1].ToString();
dgvEvents.Rows[n].Cells[2].Value = dr[2].ToString();
}
}
con.Close();
I think this can be your solution but not a good solution
dgvEvents.Rows[n].Cells[1].Value = dr[1].TrimEnd(' ').ToString();
Can anyone tell me what is the proper syntax code in using datetimepicker that would be saved directly to my Microsoft sql 2005? I'm using visual studio 2008 c#.
Here is my code:
private void button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True");
SqlDataAdapter dad = new SqlDataAdapter();
// SqlCommand cmd = new SqlCommand();
// cmd.Connection = conn;
dateTimePicker1.Format = DateTimePickerFormat.Short;
string dateStr = Convert.ToString(dateTimePicker1.Text);
dad.InsertCommand = new SqlCommand("INSERT INTO tblSchools (School_Name, Province, City, Brgy, Lot_Num, Area, Mem_Date_Rec, Cenro) VALUES(#School_Name, #Province, #City, #Brgy, #Lot_Num, #Area, #Mem_Date_Rec, #Cenro", conn);
dad.InsertCommand.Parameters.Add("#School_Name", SqlDbType.VarChar).Value = textBox1.Text;
dad.InsertCommand.Parameters.Add("#Province", SqlDbType.VarChar).Value = comboBox1.Text;
dad.InsertCommand.Parameters.Add("#City", SqlDbType.VarChar).Value = textBox2.Text;
dad.InsertCommand.Parameters.Add("#Brgy", SqlDbType.VarChar).Value = textBox4.Text;
dad.InsertCommand.Parameters.Add("#Lot_Num", SqlDbType.VarChar).Value = textBox5.Text;
dad.InsertCommand.Parameters.Add("#Area", SqlDbType.Int).Value = textBox6.Text;
dad.InsertCommand.Parameters.Add("#Mem_Date_Rec", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
dad.InsertCommand.Parameters.Add("#Cenro", SqlDbType.VarChar).Value = textBox8.Text;
conn.Open();
dad.InsertCommand.ExecuteNonQuery();
conn.Close();
}
The problem here is the datetimepicker, in my sql server Mem_Date_Rec is a datetime, so whenever I try to run it and save something on my database,
dad.InsertCommand.ExecuteNonQuery();
Keeps on saying "Incorrect syntax near '#Cenro'."
Can anyone help me out here please, it would be a really great help.
I feel like you try to insert your parameter to dad.InsertCommand command not cmd command.
dad.InsertCommand.Parameters.Add("#Mem_Date_Rec", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
Because your dad.InsertCommand has a parameter called #Mem_Date_Rec, not cmd. I have no idea what is your cmd for exactly. It's useless this case. You can't add a parameter value in an SqlCommand that doesn't have any parameter definition.
Also use using statement to dispose your SqlConnection and SqlCommand like;
using(SqlConnection conn = new SqlConnection(ConnectionString))
using(SqlCommand cmd = conn.CreateCommand())
{
//
}
If you want to write a proper syntax code, you need start reading a book, articles, blogs, examples etc..
edit
You're missing something in your SQL. Change this:
> dad.InsertCommand = new SqlCommand("INSERT INTO tblSchools
> (School_Name, Province, City, Brgy, Lot_Num, Area, Mem_Date_Rec,
> Cenro) VALUES(#School_Name, #Province, #City, #Brgy, #Lot_Num, #Area,
> #Mem_Date_Rec, #Cenro", conn);
To this
dad.InsertCommand = new SqlCommand("INSERT INTO tblSchools (School_Name, Province, City, Brgy, Lot_Num, Area, Mem_Date_Rec, Cenro) VALUES(#School_Name, #Province, #City, #Brgy, #Lot_Num, #Area, #Mem_Date_Rec, #Cenro)", conn);
INSERT INTO table (columns) values (value)
you had: INSERT INTO table (columns) values (value
I'm inserting records and one of my object is combobox. The combox is connected to the table. When i'm inserting this error appear:
Failed to convert parameter value from a DataRowView to a Int32
My code:
cn.Open();
SqlCommand Insert = new SqlCommand();
Insert.Connection = cn;
Insert.CommandType = CommandType.Text;
Insert.CommandText = "INSERT INTO Ticket VALUES (CustomerID, Date, Store, Amount, NoStub) ";
Insert.Parameters.Add("CustomerID", SqlDbType.Int).Value = cboName.SelectedValue;
Insert.Parameters.Add("Date", SqlDbType.DateTime).Value = dtpDate.Value.Date.ToString();
Insert.Parameters.Add("Store", SqlDbType.NVarChar).Value = txtStore.Text;
Insert.Parameters.Add("Amount", SqlDbType.Decimal).Value = txtAmount.Text;
Insert.Parameters.Add("NoStub", SqlDbType.Decimal).Value = txtStub.Text;
Insert.ExecuteNonQuery();
cn.Close();
Use this sample code:
command.Parameters.Add("#CustomerID", SqlDbType.Int).Value = Convert.ToInt32(storeCode);
or use
int.parse for cboName.
Change your code to the following and let the Server resolve the data type
cn.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = cn;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "INSERT INTO Ticket(CustomerID, Date, Store, Amount, NoStub)
VALUES (#CustomerID, #Date, #Store, #Amount, #NoStub) ";
sqlCmd.Parameters.AddWithValue("#CustomerID", cboName.SelectedValue);
sqlCmd.Parameters.AddWithValue("#Date", dtpDate.Value.Date.ToString());
sqlCmd.Parameters.AddWithValue("#Store", txtStore.Text);
sqlCmd.Parameters.AddWithValue("#Amount", txtAmount.Text);
sqlCmd.Parameters.AddWithValue("#NoStub", txtStub.Text);
sqlCmd.ExecuteNonQuery();
cn.Close();