MVC: second parameter for SqlCommand appearing as Null in Database - c#

I can't figure out why my second parameter (NotifyDateParameter) for my SqlCommand isn't working properly. It does not give an error, but it appears as null in my SQL Server database. The first parameter (StringParameter) appears just as intended. I could use some of your expertise right about now.
try
{
{
string connstr = #"Server=.\SQLEXPRESS;Database=ImageDB;Trusted_Connection=True;";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
string query;
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[upload].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[upload].ContentLength);
}
query = "insert into Images(ImageData, NotifyDate) values(#ImageData, #NotifyDate)";
SqlParameter StringParameter = new SqlParameter();
StringParameter.SqlDbType = SqlDbType.VarBinary;
StringParameter.ParameterName = "ImageData";
StringParameter.Value = fileData;
DateTime today = DateTime.Now;
DateTime notifyDate = today.AddDays(1);
//string notifyDateString = notifyDate.ToString();
SqlParameter NotifyDateParameter = new SqlParameter();
NotifyDateParameter.SqlDbType = SqlDbType.DateTime;
NotifyDateParameter.ParameterName = "NotifyDate";
NotifyDateParameter.Value = notifyDate;
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add(StringParameter);
cmd.Parameters.Add(NotifyDateParameter);
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
conn.Dispose();
}
}
catch (Exception e)
{
string exceptionCause = String.Format("An error occurred: '{0}'", e);
System.IO.File.WriteAllText(#"C:\Users\Nathan\Documents\Visual Studio 2013\Projects\MVCImageUpload\uploads\exception.txt", exceptionCause);
}

Well for starters do try 2 things
Replace NotifyDateParameter.ParameterName = "NotifyDate"; with NotifyDateParameter.ParameterName = "#NotifyDate"; // #added to parameter name.
Check if parameter type is SqlDbType.DateTime or SqlDbType.Date

Related

ADO.NET c# , insert query with more id's

Im new to ado.net in c#. I need to add a couple of Id's(primary keys) that will be placed in one table.These primary keys have already a value from other tables so i nedd to grab them and fill them in. The the next columns will be filled in by user => firstname,lastname,dateOfBirth,securitynumber. And i need to add the id keywords also. i have no clue how to start with it. I just know how to do an insert. So i have to get the addressId and #vehicleid,#fuelcardid from somwhere but i dont get it how?
string query = "INSERT INTO [Driver] (firstName,lastName,dateOfBirth,addressId,securityNumber,vehicleid,fuelcardid) Values (#firstName,#lastName,#dateOfBirth,#addressId,#securityNumber,#vehicleid,#fuelcardid);SELECT CAST(scope_identity() AS int)";
int? newdriverID= null;
SqlConnection connection = getConnection();
using (SqlCommand command = new SqlCommand(query, connection)) {
SqlTransaction transaction = connection.BeginTransaction();
command.Transaction = transaction;
try {
SqlParameter parDriverFirstName = new SqlParameter();
parDriverFirstName.ParameterName = "#firstName";
parDriverFirstName.SqlDbType = System.Data.SqlDbType.NVarChar;
command.Parameters.Add(parDriverFirstName);
SqlParameter parDriverLastName = new SqlParameter();
parDriverLastName.ParameterName = "#lastName";
parDriverLastName.SqlDbType = System.Data.SqlDbType.NVarChar;
command.Parameters.Add(parDriverLastName);
SqlParameter parDriverDateOfBirth = new SqlParameter();
parDriverDateOfBirth.ParameterName = "#dateOfBirth";
parDriverDateOfBirth.SqlDbType = System.Data.SqlDbType.DateTime;
command.Parameters.Add(parDriverDateOfBirth);
SqlParameter parAddressId = new SqlParameter();
parAddressId.ParameterName = "#addressId";
parAddressId.SqlDbType = System.Data.SqlDbType.Int;
command.Parameters.Add(parAddressId);
SqlParameter parDriverSecurityNr = new SqlParameter();
parDriverSecurityNr.ParameterName = "#securityNumber";
parDriverSecurityNr.SqlDbType = System.Data.SqlDbType.NVarChar;
command.Parameters.Add(parDriverSecurityNr);
SqlParameter parvehicleId = new SqlParameter();
parvehicleId.ParameterName = "#vehicleid";
parvehicleId.SqlDbType = System.Data.SqlDbType.Int;
command.Parameters.Add(parvehicleId);
SqlParameter parFuelCardID = new SqlParameter();
parFuelCardID.ParameterName = "#fuelcardid";
parFuelCardID.SqlDbType = System.Data.SqlDbType.Int;
command.Parameters.Add(parFuelCardID);
command.Parameters["#firstName"].Value = driver.FirstName;
command.Parameters["#lastName"].Value = driver.LastName;
command.Parameters["#dateOfBirth"].Value = driver.DateOfBirth;
command.Parameters["#securityNumber"].Value = driver.SecurityNumber;
command.Parameters["#addressId"].Value = addressId;
command.Parameters["#vehicleid"].Value = vehicleid; //TODO test if this works
command.Parameters["#fuelcardid"].Value = fuelcardid;
connection.Open();
newdriverID = (int)command.ExecuteScalar();
transaction.Commit();
} catch (Exception ex) {
transaction.Rollback();
throw new Exception(ex.Message);
} finally {
connection.Close();
}
}
if(newdriverID != null) {
foreach (string licensetype in driver.DriversLicenceType) {
//if a driver has no license type this will simply not loop once
//inserts a driverid and typeid into the DriversLicenceType table that can be used elsewhere
if (Alldriverlicensetypes.ContainsValue(licensetype)) {
string insertLicenseQuery = "INSERT INTO [DriverLicenseType] (driverId,licenseTypeId) Values (#driverid,#licenseID)";
SqlConnection licenseconnection = getConnection();
using (SqlCommand command = new SqlCommand(insertLicenseQuery, licenseconnection)) {
SqlTransaction transaction = connection.BeginTransaction();
command.Transaction = transaction;
try {
SqlParameter pardriverId = new SqlParameter();
pardriverId.ParameterName = "#driverid";
pardriverId.SqlDbType = System.Data.SqlDbType.Int;
command.Parameters.Add(pardriverId);
command.Parameters["#driverid"].Value = newdriverID;
SqlParameter parlicenseID = new SqlParameter();
parlicenseID.ParameterName = "#licenseID";
parlicenseID.SqlDbType = System.Data.SqlDbType.Int;
command.Parameters.Add(parlicenseID);
int key = Alldriverlicensetypes.FirstOrDefault(x => x.Value == licensetype).Key;
command.Parameters["#driverid"].Value = key;
connection.Open();
command.ExecuteNonQuery();
transaction.Commit();
} catch (Exception ex) {
transaction.Rollback();
throw new Exception(ex.Message);
} finally {
connection.Close();
}
}
} else {
//trying to add a type that is not in the database => ASK what to do here?
}
}
}//if the previous insert failed, the id will be null so dont add anything
}

How to correct error "string was not recognized as a valid DateTime" when executing program?

How to correct this error "String was not recognized as a valid DateTime"?
The error happens when trying to save the data
tried something like this with no luck as well("Checkin_Time"):
"this.Text="1/01/2019";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);"
Changed the approach to a more simplified way of sorts...
Thank you
try
{
string thisDay1 = DateTime.Now.ToString();
Bitmap bm = new Bitmap(UpdateName);
OleDbCommand cmd = new OleDbCommand("INSERT INTO [IMGs] (UPC, Checkin_Time, Photo) values (?, ?, ?)", Conn);
byte[] image_bytes = ImageToBytes(bm, ImageFormat.Png);
OleDbParameter param = new OleDbParameter();
param.OleDbType = OleDbType.Binary;
param.ParameterName = "Image";
param.Value = image_bytes;
cmd.Parameters.Add(param);
OleDbParameter param1 = new OleDbParameter();
param1.OleDbType = OleDbType.VarChar;
param1.ParameterName = "UPC";
param1.Value = textBox1.Text;
cmd.Parameters.Add(param1);
OleDbParameter param2 = new OleDbParameter();
DateTime date = DateTime.ParseExact(DateTime.Now.ToString(),"yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
param2.OleDbType = OleDbType.DBTime;//
param2.ParameterName = "Checkin_Time";
param2.Value = date;//TRIED USING THE "thisDay1" DIRECTLY & GOT SAME ERROR|FIELD IN DB IS SET AS Date/Time
cmd.Parameters.Add(param2);
// Execute the command (with no return value).
cmd.Connection = Conn;
Conn.Open();
cmd.ExecuteScalar();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (Conn.State != ConnectionState.Closed) Conn.Close();
}
Your string provider should be like this :
OleDbConnection con1 = new OleDbConnection(#" provider=Microsoft.ace.Oledb.12.0; data source=C:\fotos\IMRDATABASE.accdb; Persist Security Info=False");
for more information about connection strings see this

My Delete Query is not being working

I,m designing a CMS(campus Management System) and i wana delete some record...but its neither working nor generate any error...just return zero in "result " varaiable mentioned in code
public void DeleteAnnouncement(BusinessObject bo)
{
string ConnStr = Connection();
SqlConnection conn = new SqlConnection(ConnStr);
conn.Open();
string query = "Delete from Anouncement where AnnouncementID=#i";
SqlCommand cmd = new SqlCommand(query, conn);
SqlParameter p1 = new SqlParameter("i", bo.A_ID);
cmd.Parameters.Add(p1);
int result = cmd.ExecuteNonQuery();
conn.Close();
if (result > 0)
{
Console.WriteLine("\n\n\t============================================");
Console.WriteLine("\tAnnouncement Deleted");
Console.WriteLine("\t============================================\n\n");
}
}
SqlParameter p1 = new SqlParameter("i", bo.A_ID);
You're missing "#" in front of parameter name.
Correct: SqlParameter p1 = new SqlParameter("#i", bo.A_ID);
Your code works and deletes a record from Anouncement table, if AnnouncementID matches with the value of bo.A_ID, if value of bo.A_ID doesn't match with AnnouncementID, cmd.ExecuteNonQuery(); returns 0. If it's not deleting that means AnnouncementID doesn't match with the value of bo.A_ID.
But I suggest improve you code through using statement, this using statement ensures that Dispose is called even if an exception occurs while methods on the object are called.
string ConnStr = Connection();
string query = "Delete from Anouncement where AnnouncementID=#i";
using (SqlConnection conn = new SqlConnection(ConnStr))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
try
{
SqlParameter p1 = new SqlParameter("i", bo.A_ID);
cmd.Parameters.Add(p1);
conn.Open();
int result = cmd.ExecuteNonQuery();
conn.Close();
if (result > 0)
{
Console.WriteLine
("\n\n\t============================================");
Console.WriteLine("\tAnnouncement Deleted");
Console.WriteLine
("\t============================================\n\n");
}
}
catch (Exception ex)
{
//Do your exception handling work
}
}
}

Populating an ArrayList with MySQL data

I'm trying to populate two ArrayLists (listOfAnswers and listOfAnswerIDs) with fields from a database ('answer' and 'answer_id').
The following code seems to work perfectly fine when question_id=1 in the string cmdText. However, if I change this to 2 or 3, the ArrayLists remain empty and I don't know why. Any ideas?
I think it's to do with the string cmdGetAnswersQuery as "SELECT * FROM answers WHERE question_id=2" works...
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
MySqlDataReader reader;
ArrayList listOfAnswerIDs = new ArrayList();
ArrayList listOfAnswers = new ArrayList();
try
{
conn.Open();
string cmdText = "SELECT * FROM questions_t WHERE question_id=2";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = ddlModules.SelectedValue;
reader = cmd.ExecuteReader();
if (reader.Read())
{
lblQuestion.Text = reader["question"].ToString();
ViewState["QuestionID"] = reader["question_id"].ToString();
ViewState["AnswerID"] = reader["correct_answer_id"].ToString();
reader.Close();
string cmdGetAnswersQuery = "SELECT * FROM answers WHERE question_id=#QuestionID";
MySqlCommand cmdGetAnswers = new MySqlCommand(cmdGetAnswersQuery, conn);
cmdGetAnswers.Parameters.Add("#QuestionID", MySqlDbType.Int32);
cmdGetAnswers.Parameters["#QuestionID"].Value = ViewState["AnswerID"];
reader = cmdGetAnswers.ExecuteReader();
while (reader.Read())
{
listOfAnswerIDs.Add(reader["answer_id"].ToString());
listOfAnswers.Add(reader["answer"].ToString());
}
reader.Close();
populateAnswers(listOfAnswers, listOfAnswerIDs);
}
else
{
reader.Close();
lblError.Text = "(no questions found)";
}
}
catch
{
lblError.Text = "Database connection error - failed to insert record.";
}
finally
{
conn.Close();
}
The actual database contents are shown here:
http://i.imgur.com/3S4lV60.png
http://i.imgur.com/8A913xF.png
I can't say for sure that this is the problem, but the first thing I'd look at is this line of code:
cmdGetAnswers.Parameters["#QuestionID"].Value = ViewState["AnswerID"];
I suspect you want that to be ViewState["QuestionID"].

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();
}
}
}
}

Categories