I am trying to get date from my database into a string and comparing it with the today's date to perform some operation.
What I did as a solution but still the label isn't displaying the messages.
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//Save files to disk
FileUpload1.SaveAs(Server.MapPath("Files/" + FileName));
string FilePath = "Files/" + FileName;
//SqlCommand cmd = new SqlCommand();
DAL obj = new DAL();
using (SqlConnection conn = obj.openCon())
{
String sql = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like '" + AssignmentTitle + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
DateTime duedate = new DateTime() ;
if (dr != null && dr.HasRows)
{
while (dr.Read())
{
duedate = dr.GetDateTime(0);
}
dr.Close();
// now check if today greater than due date and update
if (duedate != null && today.Date > duedate)
{
sql = "Insert into tbl_AssignmentSubmit( Name ,AridNumber, Shift , Degree , Course , FileName ,FilePath ) values ('" + txt_Name.Text + "' , '" + txt_AridNumber.Text + "', '" + shift + "', '" + Degree + "', '" + Course + "','" + FileName + "','" + FilePath + "')";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
else
{
lbl_uploaded.Text = "Assignment can not be Submitted.You crossed the due date.";
}
}
}
}
You have to get DueDate from tbl_AssignmentUpload1 .
For example :
string strSQL = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like #AssignmentTitle ";
(SqlCommand myCommand = new SqlCommand(strSQL, cnn)) // Cnn is your sql connection
{
myCommand.Parameters.AddWithValue("#AssignmentTitle", AssignmentTitle );
using (SqlDataReader reader = myCommand.ExecuteReader())
{
while (reader.Read())
{
DateTime today1 = Convert.ToDateTime(reader["DueDate "].ToString());
}
}
}
After this you can do your insert statement
Try something like this. Ok updated with the fix for duedate.
using (SqlConnection conn = SQL.GeSQLConnection())
{
String sql = "Select DueDate from tbl_AssignmentUpload1 where AssignmentTitle like '" + AssignmentTitle + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
DateTime duedate = new DateTime();
if (dr != null && dr.HasRows)
{
while (dr.Read())
{
duedate = dr.GetDateTime(0);
}
dr.Close();
// now check if today greater than due date and update
if(duedate != null && DateTime.Today > duedate)
{
sql = "Insert into tbl_AssignmentSubmit( Name ,AridNumber, Shift , Degree , Course , FileName ,FilePath ) values ('" + txt_Name.Text + "' , '" + txt_AridNumber.Text + "', '" + shift +"', '" + Degree + "', '" + Course + "','" + FileName + "','" + FilePath + "')";
cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
else
{
lbl_uploaded.Text = "Assignment can not be Submitted.You crossed the due date.";
}
}
else
{
lbl_uploaded.Text = "No Due date was selected for the given assesment title";
}
}
Related
I'm a beginner in C# and I wrote a code that connect to my database but It give me a error
I did everything from first but nothing happened
private void btnSubmit_Click(object sender, EventArgs e)
{
string conString = "data source=DESKTOP-D5VFL9P; initial catalog = university; integrated security = True; MultipleActiveResultSets = True;";
using (SqlConnection connection = new SqlConnection(conString))
{
connection.Open();
using(SqlCommand command = new SqlCommand("INSERT INTO Persons (PersonID, LastName, FirstName, Age, City) VALUES (" + int.Parse(txtPersonID.Text) + ", '" +
txtLastName.Text + "', '" + txtFirstName.Text + "' ," + int.Parse(txtAge.Text) + ", '" + txtCity.Text + "'", connection))
{
using(SqlDataReader reader = command.ExecuteReader())
{
MessageBox.Show("Data inserted");
txtFirstName.Text = "";
txtLastName.Text = "";
txtPersonID.Text = "";
txtAge.Text = "";
txtCity.Text = "";
}
}
}
}
I want to add some values to my database
There should be a ) behind the City. Like txtCity.Text + "')".
I am not recommending this as it is definitely opens a door for SQL Injection Attack but Use below string that will work in your case:
string cmdText = "INSERT INTO Persons(PersonID,LastName,FirstName,Age,City)" +
" VALUES ('" + int.Parse(txtPersonID.Text) + "', " +
"'" + txtLastName.Text + "', " +
"'" + txtFirstName.Text + "' ,'" +
int.Parse(txtAge.Text) + "', '" +
txtCity.Text + "')"
I would do something like this:
using (SqlConnection conn = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"INSERT INTO Persons (PersonID,LastName,FirstName,Age,City) VALUES (#PersonID,#LastName,#FirstName,#Age,#City)";
cmd.Parameters.AddWithValue("#PersonID", int.Parse(txtPersonID.Text));
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#Age", int.Parse(txtAge.Text));
cmd.Parameters.AddWithValue("#City", txtCity.Text);
cmd.Connection = conn;
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
if(rowsAffected > 0)
{
MessageBox.Show("Data inserted");
}
else
{
MessageBox.Show("Failed");
}
conn.Close();
}
Can somebody tell me why the else condition is not working in the code below.
The link button in asp.net web application has following code in code behind: a parameterized SqlCommand fetch a row from a SQL Server database, the SqlDataReader rdr1.HasRows in if condition is working fine but else condition did not work.
Code updated
protected void LinkButton1_Click(object sender, EventArgs e)
{
string comid = DropDownList4.SelectedValue.ToString();
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("Select * from Commercials Where id =" + comid, con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string dur = rdr["duration"].ToString();
Char delimiter = '/';
string[] dd = DateTime.Parse(rdr["rodate"].ToString()).ToString("dd/MM/yyyy").Split(delimiter);
if (DropDownList3.SelectedValue.ToString().Contains("BOL NEWS") == true && DropDownList1.SelectedValue.ToString().Contains("After Headlines") == true)
{
SqlConnection con0 = new SqlConnection(cs);
string sql01 = "Select * from CTS Where air_time=(Select max(air_time) from CTS where air_date=#airdate and air_time Like #airtime and channel=#channel and Slot=#slot) and air_date=#airdate1";
con0.Open();
SqlCommand cmd1 = new SqlCommand(sql01, con0);
cmd1.Parameters.AddWithValue("#airdate", TextBox1.Text);
cmd1.Parameters.AddWithValue("#channel", DropDownList3.SelectedValue.ToString());
cmd1.Parameters.AddWithValue("#airtime", DropDownList2.SelectedValue.ToString().Substring(0, 2) + "%");
cmd1.Parameters.AddWithValue("#slot", DropDownList1.SelectedValue.ToString().Remove(0, 3));
cmd1.Parameters.AddWithValue("#airdate1", TextBox1.Text);
SqlDataReader rdr1 = cmd1.ExecuteReader();
while (rdr1.Read())
{
string startTime0 = rdr1["air_time"].ToString();
string addsec = rdr1["duration"].ToString();
if (rdr1.HasRows)
{
DateTime startTime1 = DateTime.ParseExact(startTime0, "HH:mm:ss", null);
string startHeadlines_ = startTime1.AddSeconds(int.Parse(addsec)).ToString("HH:mm:ss");
using (SqlConnection con2 = new SqlConnection(cs))
{
string type = "Commercial";
string year = dd[2].ToString().Substring(dd[2].ToString().Length - 2);
string HouseId = "CH1COM001" + rdr["rono"] + rdr["duration"] + "S" + dd[1] + dd[0] + year;
string sql1 = "Insert into CTS(air_date,air_time,HouseNumber,rono,Title,duration,Slot,type,channel)Values('" + TextBox1.Text + "','" + startHeadlines_ + "','" + HouseId + "','" + rdr["rono"] + "','" + rdr["slug"] + "','" + rdr["duration"] + "','" + DropDownList1.SelectedValue.Remove(0, 3) + "','" + type + "','" + DropDownList3.SelectedValue.ToString() + "')";
con2.Open();
SqlCommand InsertCmd = new SqlCommand(sql1, con2);
InsertCmd.ExecuteNonQuery();
con2.Close();
}
}
else
{
DateTime startTime = DateTime.ParseExact(DropDownList2.SelectedValue.ToString(), "HH:mm:ss", null);
string startHeadlines = startTime.AddSeconds(210).ToString("HH:mm:ss");
using (SqlConnection con1 = new SqlConnection(cs))
{
string type = "Commercial";
string year = dd[2].ToString().Substring(dd[2].ToString().Length - 2);
string HouseId = "CH1COM001" + rdr["rono"] + rdr["duration"] + "S" + dd[1] + dd[0] + year;
string sql = "Insert into CTS(air_date,air_time,HouseNumber,rono,Title,duration,Slot,type,channel)Values('" + TextBox1.Text + "','" + startHeadlines + "','" + HouseId + "','" + rdr["rono"] + "','" + rdr["slug"] + "','" + rdr["duration"] + "','" + DropDownList1.SelectedValue.ToString().Remove(0, 3) + "','" + type + "','" + DropDownList3.SelectedValue.ToString() + "')";
con1.Open();
SqlCommand InsertCmd = new SqlCommand(sql, con1);
InsertCmd.ExecuteNonQuery();
con1.Close();
}
}
}
con0.Close();
}
}
con.Close();
}
}
I want to update my sql table. I was searching here and found solutions on how to go onto that problem. But sadly it just wont update the database. I have no clue what the problem is.
I checked to sql command a couple of times for writing mistakes but couldnt find any or fixed them but still sadly nothing. I suppose it's something within the try block but cant find it out.
This is my code:
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=xxx\\xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx";
sql = "UPDATE Employees SET LastName = '" + Lnamestring + "', FirstName = '" + Fnamestring + "', Title = '" + Titelstring + "', TitleOfCourtesy = '" + ToCstring + "', BirthDate = '" + Birthdatestring + "', HireDate = '" + Hiredatestring + "', Address = '" + Adressstring + "', City = '" + Citystring + "', Region = '" + Regionstring + "', PostalCode = '" + Postalstring + "', Country = '" + Countrystring + "', HomePhone = '" + Phonestring + "', Extension = '" + Extensionsstring + "', Notes = '" + Notesstring + "', ReportsTo = '" + ReportTostring + "' WHERE EmployeeID = '" + IDstring + "'; ";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(command);
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
I hope someone can help me find my mistake.
EDIT: when i try it out it seems to work as the windows pops up with "workd" but the database is unchanged.
As MichaĆ Turczyn wrote in his answer, you have some problems with your code.
I agree with everything he wrote, but I thought you might benefit from seeing how your code should look like - so here you go:
var connetionString = "Data Source=EVOPC18\\PMSMART;Initial Catalog=NORTHWND;User ID=test;Password=test";
var sql = "UPDATE Employees SET LastName = #LastName, FirstName = #FirstName, Title = #Title ... ";// repeat for all variables
try
{
using(var connection = new SqlConnection(connetionString))
{
using(var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#LastName", SqlDbType.NVarChar).Value = Lnamestring;
command.Parameters.Add("#FirstName", SqlDbType.NVarChar).Value = Fnamestring;
command.Parameters.Add("#Title", SqlDbType.NVarChar).Value = Titelstring;
// repeat for all variables....
connection.Open();
command.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
MessageBox.Show($"Failed to update. Error message: {e.Message}");
}
Few issues with your code:
1) Use using, when working with IDisposable objects, in your case connection and command.
2) As suggested in comments, use SqlCommandParameters instead of concatenating strings for security reasons (google "preventing from SQL injections")
3) You don't execute your query! How you want it to make an impact if you don't do it? There's, for example, method like ExecuteNonQuery in SqlCommand class.
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=EVOPC18\\PMSMART;Initial Catalog=NORTHWND;User ID=test;Password=test";
sql = "UPDATE Employees SET LastName = '" + Lnamestring + "', FirstName = '" + Fnamestring + "', Title = '" + Titelstring + "', TitleOfCourtesy = '" + ToCstring + "', BirthDate = '" + Birthdatestring + "', HireDate = '" + Hiredatestring + "', Address = '" + Adressstring + "', City = '" + Citystring + "', Region = '" + Regionstring + "', PostalCode = '" + Postalstring + "', Country = '" + Countrystring + "', HomePhone = '" + Phonestring + "', Extension = '" + Extensionsstring + "', Notes = '" + Notesstring + "', ReportsTo = '" + ReportTostring + "' WHERE EmployeeID = '" + IDstring + "'; ";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(command);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Don't forget to execute the command
Try to get the stacktrace or error message from Exception as much as possible. For example: MessageBox.Show($"Can not open connection ! {e.GetBaseException().Message}, {e.StackTrace}");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "update CarTb1 set ( #RegNo , #MOdel , #Price , #Available where #Brand);";
cmd.CommandType = System.Data.CommandType.Text;
Da = new SqlDataAdapter("Select * From CarTb1", con);
Da.Fill(Dt);
cmd.Parameters.AddWithValue("#RegNo", txtRegnumber.Text);
cmd.Parameters.AddWithValue("#Brand", combBrand.Text);
cmd.Parameters.AddWithValue("#Model", txtModel.Text);
cmd.Parameters.AddWithValue("#Price", txtPrice.Text);
cmd.Parameters.AddWithValue("#Color", txtColor.Text);
cmd.Parameters.AddWithValue("#Available", combAvailable.Text);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Record Edited Successfally");
con.Close();
ClearData();
Please use the ExecuteNonQuery() instead of SqlDataAdapter:
connection.Open();
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");
This probably a simple solution, but I've got a deadline to catch and I don't know the exact problem here.
So here's the deal, I'm trying to update my table using this piece of code:
private void btn_opslaan_Click(object sender, EventArgs e)
{
string opleidingsid = "Select OpleidingsID From opleidingen Where Opleidingsnaam = '" + cb_opleiding.Text + "'";
MySqlCommand cmdid = new MySqlCommand(opleidingsid, dbconnect.connection);
dbconnect.OpenConnection();
MySqlDataReader reader = cmdid.ExecuteReader();
reader.Read();
int oplid = (int)reader.GetValue(0);
cmdid.Dispose();
reader.Close();
sql = "UPDATE leerlingen SET Naam = '_naam', Adres = '_adres', Woonplaats = '_woonplaats', Postcode = '_postcode', Email = '_email', Telefoonnummer = '_telefoonnummer', Klas = '_klas', Ovnummer = '_ovnummer', OpleidingsID = '_opleidingsid', Startdatum = '_startdatum', Einddatum = '_einddatum' WHERE LeerlingID = '_leerlingid'";
// sql = "UPDATE leerlingen set Naam = '" + txt_naam.Text + "', Adres = '" + txt_adres.Text + "', Woonplaats = '" + txt_woonplaats.Text + "', Postcode = '" + txt_postcode.Text + "', Email = '" + txt_email.Text + "', Telefoonnummer = '" + txt_telefoonnumer.Text + "', Klas = '" + txt_klas.Text + "', Ovnummer = '" + txt_ovnummer.Text + "', OpleidingsID = '" + oplID + "', Startdatum = '"+mc_startdatum.SelectionStart.Date.ToString()+"', Einddatum = '"+ mc_einddatum.SelectionStart.Date.ToString() +"' WHERE LeerlingID = '" + Int32.Parse(lbl_leerlingid.Text) + "'";
MySqlCommand cmd = new MySqlCommand(sql, dbconnect.connection);
cmd.Parameters.AddWithValue("_naam", txt_naam.Text);
cmd.Parameters.AddWithValue("_adres", txt_adres.Text);
cmd.Parameters.AddWithValue("_woonplaats", txt_woonplaats.Text);
cmd.Parameters.AddWithValue("_postcode", txt_postcode.Text);
cmd.Parameters.AddWithValue("_email", txt_email.Text);
cmd.Parameters.AddWithValue("_telefoonnummer", txt_telefoonnumer.Text);
cmd.Parameters.AddWithValue("_klas", txt_klas.Text);
cmd.Parameters.AddWithValue("_ovnummer", txt_ovnummer.Text);
cmd.Parameters.AddWithValue("_opleidingsid", oplid);
cmd.Parameters.AddWithValue("_startdatum", mc_startdatum.SelectionStart.Date.ToString());
cmd.Parameters.AddWithValue("_einddatum", mc_einddatum.SelectionStart.Date.ToString());
cmd.Parameters.AddWithValue("_leerlingid", int.Parse(lbl_leerlingid.Text));
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("opslaan gelukt");
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
throw;
}
dbconnect.CloseConnection();
this.Close();
}
I've already tried without the single quotes, it would give me the error that colomn '_leerlingid' does not exist, but that is the parameter...
Now, I dont get any errors, but it wouldn't update my database.
Any help please
P.S. Ignore the sql injection please, before this , i didn't knew better before I found out about parameters.
Try replacing your parameters with the # symbol and remove the single quotes, like this:
SQL = "UPDATE leerlingen SET Naam = #naam, Adres = #adres";
cmd.Parameters.AddWithValue("#naam", txt_naam.Text);
cmd.Parameters.AddWithValue("#adres", txt_adres.Text);
I think what you did wrong is you mustn't initialize your MySqlCommand like that. It must be like this..
MySqlCommand cmd;
cmd = dbconnect.createCommand();
cmd.CommandText = "UPDATE tableName SET firstname=#firstname, lastname=#lastname where id=#id";
cmd.Parameters.AddWithValue("#id", idTxt.Text);
cmd.Parameters.AddWithValue("#firstname", fName.Text);
cmd.Parameters.AddWithValue("#lastname", lName.Text);
cmd.ExecuteNonQuery();
when I creating a new data in c#, I make it like this ..
//values
String a = "COL1ROW1", b = "COL1ROW2";
//this is the code for mysql
String query = "Insert Into tableName(Column1, Column2)values('" + a + "','" + b + "')";
//conn is your mysqlconnection
MySqlCommand cmd = new MySqlCommand(query, conn);
//then execute it
cmd.ExecuteNonQuery();
I am using these lines of code to check if the record exists or not.
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);
int UserExist = (int)check_User_Name.ExecuteScalar();
But I am getting an error:
Object reference not set to an instance of an object.
I want to do:
if (UserExist > 0)
// Update record
else
// Insert record
ExecuteScalar returns the first column of the first row. Other columns or rows are ignored. It looks like your first column of the first row is null, and that's why you get NullReferenceException when you try to use the ExecuteScalar method.
From MSDN;
Return Value
The first column of the first row in the result set, or a null
reference if the result set is empty.
You might need to use COUNT in your statement instead which returns the number of rows affected...
Using parameterized queries is always a good practise. It prevents SQL Injection attacks.
And Table is a reserved keyword in T-SQL. You should use it with square brackets, like [Table] also.
As a final suggestion, use the using statement for dispose your SqlConnection and SqlCommand:
SqlCommand check_User_Name = new SqlCommand("SELECT COUNT(*) FROM [Table] WHERE ([user] = #user)" , conn);
check_User_Name.Parameters.AddWithValue("#user", txtBox_UserName.Text);
int UserExist = (int)check_User_Name.ExecuteScalar();
if(UserExist > 0)
{
//Username exist
}
else
{
//Username doesn't exist.
}
The ExecuteScalar method should be used when you are really sure your query returns only one value like below:
SELECT ID FROM USERS WHERE USERNAME = 'SOMENAME'
If you want the whole row then the below code should more appropriate.
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = #user)" , conn);
check_User_Name.Parameters.AddWithValue("#user", txtBox_UserName.Text);
SqlDataReader reader = check_User_Name.ExecuteReader();
if(reader.HasRows)
{
//User Exists
}
else
{
//User NOT Exists
}
sqlConnection.Open();
using (var sqlCommand = new SqlCommand("SELECT COUNT(*) FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "'", sqlConnection))
{
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
lblMessage.Text ="Record Already Exists.";
}
else
{
lblMessage.Text ="Record Not Exists.";
}
reader.Close();
reader.Dispose();
}
sqlConnection.Close();
MySqlCommand cmd = new MySqlCommand("select * from table where user = '" + user.Text + "'", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds1 = new DataSet();
da.Fill(ds1);
int i = ds1.Tables[0].Rows.Count;
if (i > 0) {
// Exist
}
else {
// Add
}
I would use the "count" for having always an integer as a result
SqlCommand check_User_Name = new SqlCommand("SELECT count([user]) FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') " , conn);
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist == 1) //anything different from 1 should be wrong
{
//Username Exist
}
try this
public static bool CheckUserData(string phone, string config)
{
string sql = #"SELECT * FROM AspNetUsers WHERE PhoneNumber = #PhoneNumber";
using (SqlConnection conn = new SqlConnection(config)
)
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#PhoneNumber", phone);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.HasRows)
{
return true; // data exist
}
else
{
return false; //data not exist
}
}
}
}
Use try catch:
try
{
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);
int UserExist = (int)check_User_Name.ExecuteScalar();
// Update query
}
catch
{
// Insert query
}
You can write as follows:
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);
if (check_User_Name.ExecuteScalar()!=null)
{
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist > 0)
{
//Username Exist
}
}
I was asking myself the same question, and I found no clear answers, so I created a simple test.
I tried to add 100 rows with duplicate primary keys and measured the time needed to process it. I am using SQL Server 2014 Developer and Entity Framework 6.1.3 with a custom repository.
Dim newE As New Employee With {.Name = "e"}
For index = 1 To 100
Dim e = employees.Select(Function(item) item.Name = "e").FirstOrDefault()
If e Is Nothing Then
employees.Insert(newE)
End If
Next
2.1 seconds
Dim newE As New Employee With {.Name = "e"}
For index = 1 To 100
Try
employees.Insert(newE)
Catch ex As Exception
End Try
Next
3.1 seconds
sda = new SqlCeDataAdapter("SELECT COUNT(regNumber) AS i FROM tblAttendance",con);
sda.Fill(dt);
string i = dt.Rows[0]["i"].ToString();
int bar = Convert.ToInt32(i);
if (bar >= 1){
dt.Clear();
MetroFramework.MetroMessageBox.Show(this, "something");
}
else if(bar <= 0) {
dt.Clear();
MetroFramework.MetroMessageBox.Show(this, "empty");
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
string s = #"SELECT * FROM tbl1 WHERE CodNo = #CodNo";
SqlCommand cmd1 = new SqlCommand(s, con);
cmd1.Parameters.AddWithValue("#CodNo", txtid.Text);
con.Open();
int records = (int)cmd1.ExecuteScalar();
if (records > 0)
{
Response.Write("<script>alert('Record not Exist')</script>");
}
else
{
Response.Write("<script>alert('Record Exist')</script>");
}
}
private void insert_data()
{
SqlCommand comm = new SqlCommand("Insert into tbl1(CodNo,name,lname,fname,gname,EmailID,PhonNo,gender,image,province,district,village,address,phonNo2,DateOfBirth,school,YearOfGraduation,exlanguage,province2,district2,village2,PlaceOfBirth,NIDnumber,IDchapter,IDpage,IDRecordNumber,NIDCard,Kankur1Year,Kankur1ID,Kankur1Mark,Kankur2Year,Kankur2ID,Kankur2Mark,Kankur3Year,Kankur3ID,Kankur3Mark) values(#CodNo,N'" + txtname.Text.ToString() + "',N'" + txtlname.Text.ToString() + "',N'" + txtfname.Text.ToString() + "',N'" + txtgname.Text.ToString() + "',N'" + txtemail.Text.ToString() + "','" + txtphonnumber.Text.ToString() + "',N'" + ddlgender.Text.ToString() + "',#image,N'" + txtprovince.Text.ToString() + "',N'" + txtdistrict.Text.ToString() + "',N'" + txtvillage.Text.ToString() + "',N'" + txtaddress.Value.ToString() + "','" + txtphonNo2.Text.ToString() + "',N'" + txtdbo.Text.ToString() + "',N'" + txtschool.Text.ToString() + "','" + txtgraduate.Text.ToString() + "',N'" + txtexlanguage.Text.ToString() + "',N'" + txtprovince1.Text.ToString() + "',N'" + txtdistrict1.Text.ToString() + "',N'" + txtvillage1.Text.ToString() + "',N'" + txtpbirth.Text.ToString() + "','" + txtNIDnumber.Text.ToString() + "','" + txtidchapter.Text.ToString() + "', '" + txtidpage.Text.ToString() + "','" + txtrecordNo.Text.ToString() + "',#NIDCard,'" + txtkankuryear1.Text.ToString() + "','" + txtkankurid1.Text.ToString() + "','" + txtkankurscore1.Text.ToString() + "','" + txtkankuryear2.Text.ToString() + "','" + txtkankurid2.Text.ToString() + "','" + txtkankurscore2.Text.ToString() + "','" + txtkankuryear3.Text.ToString() + "','" + txtkankurid3.Text.ToString() + "','" + txtkankurscore3.Text.ToString() + "')", con);
flpimage.SaveAs(Server.MapPath("~/File/") + flpimage.FileName);
string img = #"~/File/" + flpimage.FileName;
flpnidcard.SaveAs(Server.MapPath("~/Tazkiera/") + flpnidcard.FileName);
string img1 = #"~/Tazkiera/" + flpnidcard.FileName;
comm.Parameters.AddWithValue("CodNo", Convert.ToInt32(txtid.Text));
comm.Parameters.AddWithValue("image", flpimage.FileName);
comm.Parameters.AddWithValue("NIDCard", flpnidcard.FileName);
comm.ExecuteNonQuery();
con.Close();
Response.Redirect("~/SecondPage.aspx");
//Response.Write("<script>alert('Record Inserted')</script>");
}
}
Use the method Int.Parse() instead. It will work.
I had a requirement to register user. In that case I need to check whether that username is already present in the database or not. I have tried the below in C# windows form application(EntityFramework) and it worked.
var result = incomeExpenseManagementDB.Users.FirstOrDefault(x => x.userName == registerUserView.uNameText);
if (result == null) {
register.registerUser(registerUserView.fnameText, registerUserView.lnameText, registerUserView.eMailText, registerUserView.mobileText, registerUserView.bDateText, registerUserView.uNameText, registerUserView.pWordText);
} else {
MessageBox.Show("User Alreay Exist. Try with Different Username");
}