I cannot figure out what I am doing wrong here, in the debugger when I set breakpoints the strings all have string values in them, but when it comes time to insert them into the table, nothing gets put in.
the table is defined as follows
CREATE TABLE [dbo].[tblMissEvents] (
[EventID] INT IDENTITY (1, 1) NOT NULL,
[EventTime] NVARCHAR (MAX) NULL,
[MIS_Event_Action] VARCHAR (50) NULL,
[Bogey_Type] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([EventID] ASC)
);
my code:
string date = DateTime.Now.ToString();
string MISaction = text1.Text;
string BogeyType = text2.Text;
try
{
con = new SqlConnection();
con.ConnectionString =
#"data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\MissileEvents.mdf;integrated security=True;MultipleActiveResultSets=True;Connect Timeout=30";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"INSERT into tblMissEvents (EventTime, MIS_Event_Action, Bogey_Type) Values (#date, #MISaction, #BogeyType)";
cmd.Parameters.AddWithValue("#date", date);
cmd.Parameters.AddWithValue("#MISaction", MISaction);
cmd.Parameters.AddWithValue("#BogeyType", BogeyType);
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
con.Close();
Any thoughts?? I don't get an exception, just no entry into my table.
edit for Arshad:
con = new SqlConnection();
con.ConnectionString =
#"data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\MissileEvents.mdf;integrated security=True;MultipleActiveResultSets=True;Connect Timeout=30";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"INSERT into tblMissEvents (MIS_Event_Action, Bogey_Type) Values (#date, #MISaction, #BogeyType)";
cmd.Parameters.AddWithValue("#date", date);
cmd.Parameters.AddWithValue("#MISaction", MISaction);
cmd.Parameters.AddWithValue("#BogeyType", BogeyType);
cmd.Connection = con;
cmd.ExecuteNonQuery();
UPDATE:: The code was fine, it was making a copy of the DB in my bin\Debug directory and thats where all the data was going. Probably something with my connection string setup. Thanks all!
You can pass null value also as :
cmd.CommandText =
"INSERT into tblMissEvents (EventTime, MIS_Event_Action, Bogey_Type)
Values (#eventTime, #MISaction, #BogeyType)";
cmd.Parameters.AddWithValue("#eventTime", DBNull.Value);
cmd.Parameters.AddWithValue("#MISaction", MISaction);
cmd.Parameters.AddWithValue("#BogeyType", BogeyType);
Update 1
cmd.CommandText =
"INSERT into tblMissEvents (EventTime,MIS_Event_Action, Bogey_Type)
Values
(#date, #MISaction, #BogeyType)";
Update 2
int RowUpdated=cmd.ExecuteNonQuery();
MessageBox.Show("Number of row updated"+RowUpdated);
Related
I am using visual studio 2013 and oracle database.I want execute multiple create table queries at once in single oraclecommand is it possible ? I am trying following but not working
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "create table test(name varchar2(50) not null)"+"create table test2(name varchar2(50) not null)";
//+ "create table test3(name varchar2(50) not null)"+"create table test3(name varchar2(50) not null)";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
Got error at cmd.ExecuteNonQuery();
In order to execute more than one command put them in begin ... end; block.
And for DDL statements (like create table) run them with execute immediate. This code worked for me:
OracleConnection con = new OracleConnection(connectionString);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText =
"begin " +
" execute immediate 'create table test1(name varchar2(50) not null)';" +
" execute immediate 'create table test2(name varchar2(50) not null)';" +
"end;";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
con.Close();
More info: Executing SQL Scripts with Oracle.ODP
Have you tried
cmd.CommandText = "create table test(name varchar2(50) not null);"+"create table test2(name varchar2(50) not null);";
I'm trying to insert new values into my database using visual studio and here is my code:
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = dbconnectionstring;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Data_ConfigInfo (TypeID, Name, ValidFromDate, ValidToDate, ValidFromSOP, ValidToSOP, Description)" +
"VALUES(#TypeID, #Name, #ValidFromDateTime, #ValidToDateTime, #ValidFromSOP, #ValidToSOP, #Description)";
cmd.Parameters.AddWithValue("TypeID", Logg.TypeID);
cmd.Parameters.AddWithValue("Name", Logg.Name);
if(Logg.ValidFrom.Equals(null)) {
cmd.Parameters.AddWithValue("#ValidFromDateTime", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#ValidFromDateTime", Logg.ValidFrom);
}
if (Logg.ValidTo.Equals(null))
{
cmd.Parameters.AddWithValue("#ValidToDateTime", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#ValidToDateTime", Logg.ValidFrom);
}
cmd.Parameters.AddWithValue("#ValidFromSOP", Logg.ValidFromSOP);
cmd.Parameters.AddWithValue("#ValidToSOP", Logg.ValidToSOP);
cmd.Parameters.AddWithValue("#Description", Logg.Description);
cmd.ExecuteNonQuery();
conn.close();
conn.dispose();
But at the line
cmd.ExecuteNonQuery();
I get the error
invalid column name for ValidToDateTime and ValidFromDateTime.
Both are datetime variables. I can't seem to find the error. Any ideas?
This is how my datatable looks
Your DB table has columns ValidFromDateTime, ValidToDateTime, but your column list in the INSERT statement has ValidFromDate, ValidToDate. Are you sure that it is not a typo when posting here?
Did you forgot '#'?
cmd.Parameters.AddWithValue("TypeID", Logg.TypeID);
cmd.Parameters.AddWithValue("Name", Logg.Name);
cmd.Parameters.AddWithValue("#TypeID", Logg.TypeID);
cmd.Parameters.AddWithValue("#Name", Logg.Name);
I have a database that contains a Customer table with the following columns : CustID, CustName, ICNumber, ContactNumber and Address. It is a service-based database.
string localdb = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(localdb);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Customer(CustID,CustName,ICNumber,ContactNumber,Address)values(#CustID,#CustName,#ICNumber,#ContactNumber,#Address)", con);
cmd.Parameters.AddWithValue("#CustID", txtCustID.Text);
cmd.Parameters.AddWithValue("#CustName", txtCustName.Text);
cmd.Parameters.AddWithValue("#ICNumber", txtICNum.Text);
cmd.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.ExecuteNonQuery();
con.Close();
The code compiles and runs. The problem I am having is that the record is not added into the table after cmd.ExecuteNonQuery(); is called.
Why is the record not showing up in the database table?
You forgot to close the quotes " on the insert command. It is nice to use try/catch to avoid problems with your insert, for sample:
string localdb = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
try
{
SqlConnection con = new SqlConnection(localdb))
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Customer(CustID, CustName, ICNumber, ContactNumber, Address) VALUES (#CustID, #CustName, #ICNumber, #ContactNumber, #Address)", con);
cmd.Parameters.AddWithValue("#CustID", txtCustID.Text);
cmd.Parameters.AddWithValue("#CustName", txtCustName.Text);
cmd.Parameters.AddWithValue("#ICNumber", txtICNum.Text);
cmd.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.ExecuteNonQuery();
}
catch
{
// some errors
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
I am trying to get all the details of a User in an Access database. But i cant seem to save each columns value to a label. Here is the code i am using.
Also UserId has a value assigned to it already
string connString = (#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=DataDirectory|HorseDB.mdb");
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"SELECT * FROM [Users] WHERE [UserId] = #UserId ";
cmd.Parameters.AddWithValue("#UserId", UserId);
OleDbDataReader dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
accountUserIdLabel.Text = dbReader.GetValue(0).ToString();
//Will add other labels once this works
}
dbReader.Close();
conn.Close();
I am using this method to insert a row into a table:
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.Connection.Open();
string commandLine = #"INSERT INTO Wanted (clientid,userid,startdate,enddate) VALUES" +
"(#clientid, #userid, #startdate, #enddate);";
cmd.CommandText = commandLine;
cmd.Parameters.AddWithValue("#clientid", userId);
cmd.Parameters.AddWithValue("#userid", "");
cmd.Parameters.AddWithValue("#startdate", start);
cmd.Parameters.AddWithValue("#enddate", end);
cmd.ExecuteNonQuery();
cmd.Connection.Close();
I hav also id column that have Auto Increment .
And i want to know if it possible to get the id that is created when i insert a new row.
You can access the MySqlCommand LastInsertedId property.
cmd.ExecuteNonQuery();
long id = cmd.LastInsertedId;
MySqlConnection connect = new MySqlConnection(connectionStringMySql);
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connect;
cmd.Connection.Open();
string commandLine = #"INSERT INTO Wanted (clientid,userid,startdate,enddate) "
+ "VALUES(#clientid, #userid, #startdate, #enddate);";
cmd.CommandText = commandLine;
cmd.Parameters.AddWithValue("#clientid", userId);
**cmd.Parameters["#clientid"].Direction = ParameterDirection.Output;**
cmd.Parameters.AddWithValue("#userid", "");
cmd.Parameters.AddWithValue("#startdate", start);
cmd.Parameters.AddWithValue("#enddate", end);
cmd.ExecuteNonQuery();
cmd.Connection.Close();
Basically you should add this to end of your CommandText:
SET #newPK = LAST_INSERT_ID();
and add another ADO.NET parameter "newPK". After command is executed it will contain new ID.