Getting SSL Provider Error when using IntegratedSecurity - c#

SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = "Data Source=.;Database = deptStore;Integrated Security = true;";
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into Employee values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "','" + TextBox12.Text + "','" + TextBox13.Text + "')";
cmd.Connection = cnn;
cmd.ExecuteNonQuery();
Response.Write("Record Save");
cnn.Close();
But I am getting following Error:
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = "Data Source=.;Database = deptStore;Integrated Security = true;";
cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into Employee values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "','" + TextBox12.Text + "','" + TextBox13.Text + "')";
cmd.Connection = cnn;
cmd.ExecuteNonQuery();
Response.Write("Record Save");
cnn.Close();
But iam getting following Error:
SqlException was unhandled by user code
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Kindly help me to understand the error and rectify it.

Make sure you have enabled TCP/IP in SQL Server Configuration Manager: Enable Network Access in SQL Server Configuration Manager
Also, Start the SQL Server Browser Service: Start and Stop the SQL Server Browser Service

Related

Problem with inserting unique value into SQL Server in C#

My code doesn't catch the exception when I try to add the same user to the database and I don't really know how to change it.
try
{
SqlConnection.Open();
string sqlZapytanie = "INSERT INTO Host Values('" + host.Name + "','" +
host.Surname + "'," + host.PESEL + ",'" + host.City + "','" + host.Street + "', '" + host.House_number + "','" + host.Apartament_number + "','" + host.e_mail + "'," + host.Phone_number + ",'"+host.Login+"')";
try
{
SqlCommand.Connection = SqlConnection;
SqlCommand.CommandText = sqlZapytanie;
SqlCommand.ExecuteNonQuery();
}
catch(SqlException sqlex)
{
MessageBox.Show(sqlex.Message, "Zduplikowany użytkownik.", MessageBoxButton.OK);
}
Perhaps the error to be returned is not type SqlException but type Exception.

inserting data from excel to sql table

Am getting an error while inserting data from excel to the database table.
this is the error Incorrect syntax near 'NAME'
this is my code:
protected void btninsert_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
conStr = ConfigurationManager.ConnectionStrings["SqlConString"].ConnectionString;
SqlConnection con = new SqlConnection(conStr);
SqlCommand com = new SqlCommand("insert into MedicalItems (ITEM NAME,GROUP,ITEM TYPE,COST PRICE,SELLING PRICE,PURCHASE UOM,PURCHASE PACKAGING,DISPENSING UOM,QTY ON HAND,EXPIRY DATE,REORDER LEVEL,REORDER QUANTITY,BATCH#) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "','" + g1.Cells[4].Text + "','" + g1.Cells[5].Text + "','" + g1.Cells[6].Text + "','" + g1.Cells[7].Text + "','" + g1.Cells[8].Text + "','" + g1.Cells[9].Text + "','" + g1.Cells[10].Text + "','" + g1.Cells[11].Text + "','" + g1.Cells[12].Text + "','" + g1.Cells[13].Text + "')", con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
Label2.Text = "Records inserted successfully";
}
Wrap the column names within [] like [ITEM NAME], for all the columns with whitespaces.

"ExecuteNonQuery: Connection property has not been initialized."

Here is the code:
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/charlyn_dale/Documents/Visual Studio 2010/Projects/LMS/WindowsFormsApplication2/Accounts.accdb;Persist Security Info=False");
OleDbCommand conn = new OleDbCommand(str);
con.Open();
string query = "insert into Account ([Username],[Password],FirstName,MiddleName,LastName,Age,Section,Gender,Address,AccountStatus) values('" + txt1.Text + "','" + txt2.Text + "','" + txt4.Text + "','" + txt5.Text + "','" + txt6.Text + "','" + txt7.Text + "','" + txt8.Text + "','" + cmb2.Text + "','" + txt9.Text + "','" + cmb1.Text + "')";
OleDbCommand cmd = new OleDbCommand(query, con);
conn.ExecuteNonQuery();
MessageBox.Show("Registration Success!");
con.Close();
and the error is:
Connection property has not been initialized
There are 3 main issues in your Access DB connection:
OleDbConnection connection string property has not initialized when opening OLE DB connection (note that con is different from conn in this context).
The connection string wrongly assigned to variable conn which declared as OleDbCommand, use OleDbConnection instead.
The connection string data source path seems invalid by using slash sign for directory separator (assuming target file exists in Windows folder), use backslash escape sequence (\\) or single backslash with literal string instead (e.g. #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\......").
Hence, the correct connection sequence should be like this:
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\charlyn_dale\\Documents\\Visual Studio 2010\\Projects\\LMS\\WindowsFormsApplication2\\Accounts.accdb;Persist Security Info=False");
using (OleDbConnection conn = new OleDbConnection(str))
{
conn.Open();
// security tips: better use parameter names to prevent SQL injection on queries
// and put value checking method for all textbox values (sanitize input)
string query = "insert into Account ([Username],[Password],FirstName,MiddleName,LastName,Age,Section,Gender,Address,AccountStatus) values ('" + txt1.Text + "','" + txt2.Text + "','" + txt4.Text + "','" + txt5.Text + "','" + txt6.Text + "','" + txt7.Text + "','" + txt8.Text + "','" + cmb2.Text + "','" + txt9.Text + "','" + cmb1.Text + "')";
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
conn.ExecuteNonQuery();
}
... // other stuff
conn.Close();
}
NB: using statements added due to OLE DB connection should be disposed immediately after usage to free up resources.
Similar issues:
get an error as ExecuteNonQuery:Connection property has not been initialized
ExecuteNonQuery: Connection property has not been initialized (access database)
ExecuteNonQuery: Connection property has not been initialized

Code Doesn't work. C# Execute Non Query

string conStr = null;
SqlCommand cmd;
SqlConnection cnn;
string sql = null;
conStr = "Data Source=DELL-PC\\SQLEXPRESS;Initial Catalog=DBMSI;Integrated Security=True";
sql = "insert into CEC_Employee values('"+empid + "','" + name + "','" + fname + "','" + mname + "','" + lname + "','" + address + "','" + postcode + "','" + job + "','" + sdate + "','" + whours + "','" + sph + "','" + spa + "','" + location + "','" + working + "','" + gender + "','" + dob + "','" + pn + "','" + exp + "','" + vtype + "','" + vexp + "','" + qualification + "','" + email + "','" + number + "','" + nin + "','" + sort + "','" + acc + "','" + bank + "','" + nname + "','" + rel + "','" + addkin + "','" + cnokin + "','" + emailkin + "')";
cnn = new SqlConnection(conStr);
try
{
cnn.Open();
cnn = new SqlConnection(conStr);
cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Open();
MessageBox.Show("Employee Details registered Succesffuly");
// Keeps on moving to the Exception part of the code. Doesn't execute the try portion of the program.
}
catch (Exception ex)
{
MessageBox.Show("Error Occoured - Employee Details were not recorded");
}
Found the code online. Please help to make it work. Thanks!
Hopefully your primary key on CEC_Employee isn't "empid", and if it is set to be an autonumber, like IDENTITY(1,1), the SQL command will fail as it won't let you hand it a primary key value.
This is speculation of course, since you haven't posted the actual exception message or stack trace.

Transaction commands executing but not reflecting in db c#

The below code is to insert student details and run 3 stored procedures (all on cmd1). I have used
transaction and rollback for the same. All 4 executenonquery() are executed but nothing is reflected in the database.
Can anyone explain what is wrong or why it is not affecting the database?
con.Open();
SqlCommand cmd1 = con.CreateCommand();
SqlTransaction transaction1;
transaction1 = con.BeginTransaction("Save Update Student");
cmd1.Connection = con;
cmd1.Transaction = transaction1;
try
{
//sp to autogenerate student code in system..
cmd1.CommandText = "sp_AutoGenerateStudentCode";
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#std", SqlDbType.VarChar).Value = cb_std.SelectedItem.ToString();
cmd1.Parameters.Add("#div", SqlDbType.VarChar).Value = cb_div.SelectedItem;
cmd1.Parameters.Add("#Rollno", SqlDbType.Int).Value = txt_roll.Text;
cmd1.Parameters.Add("#ReturnValue", SqlDbType.VarChar).Value = txt_name.Text;
cmd1.ExecuteNonQuery();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "insert into StudentMaster(GrNo,Name,DOB,Std,Div,RollNo,MobileNo,Address,TelNo,FathersName,FathersProfession,MothersName,MothersProfession,Age,Year,status,DOE,BookNo,FeesStatus,FthrsQlfction,FthrsOfcAdd,FthrsPhone,MthrsPhone,MthrsOfcAdd,MthrsQlfction,Bloodgrp,caste,Nationality,MotherTongue,PreviousSchool,Religion,height,weight,sex,SCode,EmailId)values ('" + txt_Grno.Text + "','" + txt_name.Text + "',#DOB,'" + cb_std.SelectedItem + "','" + cb_div.SelectedItem + "','" + txt_roll.Text + "','" + txt_mobile.Text + "','" + Rtxt_ResiAdd.Text + "','" + txt_Phone.Text + "','" + txt_fname.Text + "','" + txt_fOccu.Text + "','" + txt_mName.Text + "','" + txt_mOccu.Text + "','" + txt_Age.Text + "',getDate(),'" + cb_status.SelectedItem + "',#DOE,'" + txt_bookno.Text + "','" + cb_feestat.SelectedItem + "','" + txt_fQualificatn.Text + "','" + Rtxt_fOfcAdd.Text + "','" + txt_fPhone.Text + "','" + txt_mPhone.Text + "','" + Rtxt_mOfcAdd.Text + "','" + txt_mQualificatn.Text + "','" + cb_BldGrp.SelectedItem + "','" + txt_caste.Text + "','" + txt_Nationality.Text + "','" + txt_MthrTng.Text + "','" + txt_PrevSchool.Text + "','" + txt_Relgn.Text + "','" + masktb_hgt.Text + "','" + masktb_wgt.Text + "','" + cb_Gender.SelectedItem + "','scode','" + txt_email.Text + "')";
cmd1.Parameters.Add("#DOE", SqlDbType.DateTime).Value = dateTimePicker1.Value;
cmd1.Parameters.Add("#DOB", SqlDbType.DateTime).Value = dateTimePicker2.Value;
cmd1.ExecuteNonQuery();
cmd1.CommandText = "PrimaryFeesMainUpdate";
cmd1.ExecuteNonQuery();
cmd1.CommandText = "FEE";
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Added Successfully", "Success");
button2_Click(null, null);
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction1.Rollback();
}
catch (Exception ex2)
{
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
con.Close();
Call Commit after you execute the last command:
cmd1.ExecuteNonQuery();
transaction1.Commit();
You must commit your transaction, as follows:
con.Open();
SqlCommand cmd1 = con.CreateCommand();
SqlTransaction transaction1;
transaction1 = con.BeginTransaction("Save Update Student");
cmd1.Connection = con;
cmd1.Transaction = transaction1;
try
{
//sp to autogenerate student code in system..
cmd1.CommandText = "sp_AutoGenerateStudentCode";
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#std", SqlDbType.VarChar).Value = cb_std.SelectedItem.ToString();
cmd1.Parameters.Add("#div", SqlDbType.VarChar).Value = cb_div.SelectedItem;
cmd1.Parameters.Add("#Rollno", SqlDbType.Int).Value = txt_roll.Text;
cmd1.Parameters.Add("#ReturnValue", SqlDbType.VarChar).Value = txt_name.Text;
cmd1.ExecuteNonQuery();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "insert into StudentMaster(GrNo,Name,DOB,Std,Div,RollNo,MobileNo,Address,TelNo,FathersName,FathersProfession,MothersName,MothersProfession,Age,Year,status,DOE,BookNo,FeesStatus,FthrsQlfction,FthrsOfcAdd,FthrsPhone,MthrsPhone,MthrsOfcAdd,MthrsQlfction,Bloodgrp,caste,Nationality,MotherTongue,PreviousSchool,Religion,height,weight,sex,SCode,EmailId)values ('" + txt_Grno.Text + "','" + txt_name.Text + "',#DOB,'" + cb_std.SelectedItem + "','" + cb_div.SelectedItem + "','" + txt_roll.Text + "','" + txt_mobile.Text + "','" + Rtxt_ResiAdd.Text + "','" + txt_Phone.Text + "','" + txt_fname.Text + "','" + txt_fOccu.Text + "','" + txt_mName.Text + "','" + txt_mOccu.Text + "','" + txt_Age.Text + "',getDate(),'" + cb_status.SelectedItem + "',#DOE,'" + txt_bookno.Text + "','" + cb_feestat.SelectedItem + "','" + txt_fQualificatn.Text + "','" + Rtxt_fOfcAdd.Text + "','" + txt_fPhone.Text + "','" + txt_mPhone.Text + "','" + Rtxt_mOfcAdd.Text + "','" + txt_mQualificatn.Text + "','" + cb_BldGrp.SelectedItem + "','" + txt_caste.Text + "','" + txt_Nationality.Text + "','" + txt_MthrTng.Text + "','" + txt_PrevSchool.Text + "','" + txt_Relgn.Text + "','" + masktb_hgt.Text + "','" + masktb_wgt.Text + "','" + cb_Gender.SelectedItem + "','scode','" + txt_email.Text + "')";
cmd1.Parameters.Add("#DOE", SqlDbType.DateTime).Value = dateTimePicker1.Value;
cmd1.Parameters.Add("#DOB", SqlDbType.DateTime).Value = dateTimePicker2.Value;
cmd1.ExecuteNonQuery();
cmd1.CommandText = "PrimaryFeesMainUpdate";
cmd1.ExecuteNonQuery();
cmd1.CommandText = "FEE";
cmd1.ExecuteNonQuery();
// COMMIT THE TRANSACTION!
transaction1.Commit();
con.Close();
MessageBox.Show("Record Added Successfully", "Success");
button2_Click(null, null);
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction1.Rollback();
}
catch (Exception ex2)
{
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
con.Close();

Categories