Wrong Format of the initialization string in ADO.NET - wpf

I just have a simply method show below:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
string sqlcmdString = string.Format("UPDATE Bills SET Name = '#name', Time = '#time', Product = '#pro', Price = #money WHERE Name = '#value';");
using (SqlConnection con = new SqlConnection(sqlcmdString))
using (SqlCommand cmd = new SqlCommand("dbo.Bills", con))
{
// tell ADO.NET it's a stored procedure (not inline SQL statements)
cmd.CommandType = CommandType.StoredProcedure;
// define parameters
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 100).Value = tb_TenKH.Text;
cmd.Parameters.Add("#time", SqlDbType.DateTime).Value = cb_Thoigian.Text;
cmd.Parameters.Add("#pro", SqlDbType.NVarChar, 100).Value = tb_SanPham.Text;
cmd.Parameters.Add("#money", SqlDbType.Money).Value = tb_ThanhTien.Text;
cmd.Parameters.Add("#value", SqlDbType.NVarChar, 100).Value = cellvalue;
// open connection, execute stored procedure, close connection again
con.Open();
if (cmd.ExecuteNonQuery() > 0)
{
//dosomething
}
else
{
MessageBox.Show("Failed!!!");
}
con.Close();
}
}
This lines could not be run. When i debug it, it shows error:
System.ArgumentException: 'Format of the initialization string does
not conform to specification starting at index 0.'
I aware that something went wrong in my sqlcmdString maybe about syntax, but I couldn't determine it. Please give me a help.

I'm wrong in syntax: I should use like below:
string sqlcmdString = string.Format("UPDATE Bills SET Name = '#name', Time = '#time', Product = '#pro', Price = #money WHERE Name = '#value';");
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(sqlcmdString, con))
{
cmd.CommandType = CommandType.Text;
// define parameters
cmd.Parameters.Add("#name", SqlDbType.NVarChar, 100).Value = tb_TenKH.Text;
cmd.Parameters.Add("#time", SqlDbType.DateTime).Value = cb_Thoigian.Text;
cmd.Parameters.Add("#pro", SqlDbType.NVarChar, 100).Value = tb_SanPham.Text;
cmd.Parameters.Add("#money", SqlDbType.Money).Value = tb_ThanhTien.Text;
cmd.Parameters.Add("#value", SqlDbType.NVarChar, 100).Value = cellvalue;
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Thành Công!!!");
if (passrow != null)
{
string[] result_back = { tb_TenKH.Text, cb_Thoigian.Text, tb_SanPham.Text, tb_ThanhTien.Text };
passrow(result_back);
{
this.Hide();
}
}
}
else
{
MessageBox.Show("Thất Bại!!!");
}
con.Close();
}
}

Related

How to connect to SQL Server

I am trying to connect to my database, I am beginner to the repository, dependency injection. I couldn't connect to the database.
How can I resolve this issue?
This is my code:
Controller:
public ActionResult Create(FormCollection collection)
{
try
{
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Repository:
public UserMaster Add(UserMaster item)
{
using (SqlConnection sqlCon = new SqlConnection(connectionstring))
{
sqlCon.Open();
string query = "INSERT INTO Employee
VALUES (#ID, #Name, #City, #Address)";
for (int i = 0; i <= 100; i++)
{
SqlCommand sqlcmd = new SqlCommand(query, sqlCon);
sqlcmd.Parameters.AddWithValue(ID = i, Name = "newride", City = "newride", Address = "USA");
}
}
return item;
}
The connection is made using the connection string and the SqlConnection class - that seems to be fine in your code.
BUT: the way you're trying to insert values is all wrong - you need to use something like this:
using (SqlConnection sqlCon = new SqlConnection(connectionstring))
{
sqlCon.Open();
// SPECIFY the column you insert into!
// Without the # "query" is not recognized as a multiline string... that's why the PO is getting that VALUES does not exists in the current context...
string query = #"INSERT INTO Employee (ID, Name, City, Address)
VALUES (#ID, #Name, #City, #Address)";
for (int i = 0; i <= 100; i++)
{
SqlCommand sqlcmd = new SqlCommand(query, sqlCon);
// set the individual parameters, and AVOID "AddWithValue"
sqlcmd.Parameters.Add("#ID", SqlDbType.Int).Value = i;
sqlcmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = "newride";
sqlcmd.Parameters.Add("#City", SqlDbType.VarChar, 100).Value = "newride";
sqlcmd.Parameters.Add("#Address", SqlDbType.VarChar, 100).Value = "USA";
// and then *EXECUTE* the SqlCommand to actually RUN the INSERT
sqlcmd.ExecuteNonQuery();
}
}

Query for instance_name, port number in format in SQL Server

I need result in below format, with current connection port. Can someone help me?
servername\instance,3000
Thanks
The following shows you code you can run as c# Console app to get what you want. If you are already in SQL Management Studio, then you just need to execute the commands directly:
static void Main(string[] args)
{
using (var conn = new SqlConnection("Integrated Security=true; Initial Catalog=dbname;Data Source=servername"))
{
using (var cmd = new SqlCommand("SELECT SERVERPROPERTY('ServerName'), SERVERPROPERTY('InstanceName')", conn))
{
string serverName = "";
string instanceName = "";
cmd.CommandType = System.Data.CommandType.Text;
conn.Open();
var rdr = cmd.ExecuteReader();
if (rdr.Read())
{
serverName = rdr.GetString(0);
if (!rdr.IsDBNull(1))
{
instanceName = rdr.GetString(1);
}
}
rdr.Close();
Console.WriteLine("Server name of this connection is: " + serverName + ". Instance of this connection is: " + instanceName);
}
using (var cmd = new SqlCommand("xp_readerrorlog", conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
var param = cmd.CreateParameter();
param.ParameterName = "#ArchiveID";
param.DbType = System.Data.DbType.Int32;
param.Value = 0;
cmd.Parameters.Add(param);
param = cmd.CreateParameter();
param.ParameterName = "#LogType";
param.DbType = System.Data.DbType.Int32;
param.Value = 1;
cmd.Parameters.Add(param);
param = cmd.CreateParameter();
param.ParameterName = "#Filter1Text";
param.DbType = System.Data.DbType.String;
param.Value = "Server is listening on";
cmd.Parameters.Add(param);
var rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr.GetString(2));
}
rdr.Close();
}
}
Console.ReadKey();
}
Note that if your server is using default instance (as mine does) then instance name is NULL.

Login for users of different positions

I am sort of new to login feature for projects and am trying to do logins for my group, which consists of 3 users, namely Nurse, Patient and Pharmacist. I think I am about to complete the loin process but I have a problem with one of my methods, getPosition() in my LoginDAO.cs. So far, I have not done any login codes for patient and pharmacist as i will need my group mates' parts for it to work, but shown below is what I have done. Somehow, login(string nric, string pw) works, but not getPosition(string nric). This is the error that i get from my error log:
Exception: Must declare the scalar variable "#paraNRIC". Source: LoginDAO.getPosition
Thanks in advance :D
protected void btnLogin_Click(object sender, EventArgs e)
{
login login = new login();
login.nric = tbLoginID.Text;
login.pw = tbPassword.Text;
if (login.userLogin(login.nric, login.pw))
{
if (login.getPosition(login.nric) == "Nurse")
{
Response.Redirect("Nurse.aspx");
}
else if (login.getPosition(login.nric) == "Patient")
{
Response.Redirect("Patient.aspx");
}
else if (login.getPosition(login.nric) == "Pharmacist")
{
Response.Redirect("PharmacistDisplay.aspx");
}
}
else
{
lblErr.Text = "Invalid account.";
}
}
public bool login(string nric, string pw)
{
bool flag = false;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Password from Position");
sqlStr.AppendLine("Where NRIC = #paraNRIC");
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
cmd.Parameters.AddWithValue("#paraNRIC", nric);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt == null)
{
flag = false;
}
else
{
string dbhashedpw = dt.Rows[0]["Password"].ToString();
flag = Helper.VerifyHash(pw, "SHA512", dbhashedpw);
}
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("NurseDAO.login", sqlStr.ToString(), exc);
}
return flag;
}
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
myconn.Open();
result = cmd.ExecuteNonQuery();
dbPosition = dt.Rows[0]["Position"].ToString();
myconn.Close();
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("LoginDAO.getPosition", sqlStr.ToString(), exc);
}
return dbPosition;
`}
Your error is here:
SqlCommand cmd = new SqlCommand();
// lines omitted
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Note that you are instantiating cmd twice. The code adds the parameters to the first SqlCommand instance, but executes the second instance.
To resolve, ensure you declare the parameters on the instance of SqlCommand you invoke:
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
// remove this line: SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
// move parameter declaration until after you declare cmd
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
SqlCommand cmd = new SqlCommand(sqlStr.ToString(), myconn);
// add the parameters here:
cmd.Parameters.AddWithValue("#paraNRIC", nric);
// code continues
You could change this line
sqlStr.AppendLine("where NRIC = #paraNRIC");
To This
sqlStr.AppendLine("where NRIC = '" + nric + "'");
and avoid parameters altogether.

SQL CLR executes with multiples sql statements

I need a SQL CLR that executes with multiple sql statements, i.e., with update queries, select queries and stored procedures to create a stored procedure in the database
[Microsoft.SqlServer.Server.SqlProcedure]
public static void pExecuteAuthorization(SqlInt32 id) {
string name = "";
string surname = "";
using (SqlConnection connection = new SqlConnection("context connection=true")) {
string sql = "UPDATE tTest SET Sequence = ISNULL(Sequence,0) + 1 WHERE Id = " + id;
using (SqlCommand command = new SqlCommand(sql, connection)) {
connection.Open();
int valRet = command.ExecuteNonQuery();
if (valRet > 0)
{
command.CommandText = "SELECT Name, Surname FROM tAuthorization WHERE Id = 1";
SqlParameter param = command.Parameters.Add("#Name", SqlDbType.VarChar, 50);
param.Direction = ParameterDirection.Output;
param = command.Parameters.Add("#Surname", SqlDbType.VarChar, 20);
param.Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
name = command.Parameters["#Name"].Value.ToString();
surname = command.Parameters["#Surname"].Value.ToString();
if (name != "" && surname != "")
{
command.CommandText = "SELECT ...";
SqlDataReader dr = command.ExecuteReader();
if (dr.Read())
{
//other queries more
}
}
}
}
SqlContext.Pipe.ExecuteAndSend(command);
}
}
But when I execute the sp created, only I get the result of select, and it does not execute the other queries

Database Updating

I have a web app, where when a page loads, the address details are extracted from the database and displayed in the corresponding text-fields. However when I try to update and save the data, the data doesn't get updated.
However the same works fine when the extraction of data happens through the click of a button.
here's the code :
public partial class Address : System.Web.UI.Page
{
string global;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
global = Session["ID"].ToString();
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Server = INLD50045747A\\SQLEXPRESS; Database = MyDatabase;User ID = sa; Password = Welcome1; Trusted_Connection = False;");
//SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT PermanentAdd,PermanentAdd2, HomePlace, HomeState, HomePin FROM EMPLOYEE_FULLADDRESS_TABLE WHERE EmployeeID = '" + global + "'", con);
SqlDataReader x = cmd.ExecuteReader();
while (x.Read())
{
TextBox1.Text = (string)x["PermanentAdd"];
TextBox1.Enabled = false;
TextBox5.Text = (string)x["PermanentAdd2"];
TextBox5.Enabled = false;
TextBox2.Text = (string)x["HomePlace"];
TextBox2.Enabled = false;
TextBox3.Text = (string)x["HomeState"];
TextBox3.Enabled = false;
State.Items.FindByText(State.SelectedItem.Text).Selected = false;
State.Items.FindByText(TextBox3.Text).Selected = true;
State.Enabled = false;
TextBox4.Text = (string)x["HomePin"];
TextBox4.Enabled = false;
}
x.Close();
con.Close();
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
try
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Server = INLD50045747A\\SQLEXPRESS; Database = MyDatabase;User ID = sa; Password = Welcome1; Trusted_Connection = False;");
//System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True;User Instance=True");
con.Open();
// global = Session["ID"].ToString();
//string insert = "UPDATE EMPLOYEE_FULLADDRESS_TABLE SET PermanentAdd = #PermanentAdd, PermanentAdd2 = #PermanentAdd2, HomePlace = #HomePlace, HomeState= #HomeState, HomePin= #HomePin where EmployeeID = '" + global + "'";
SqlCommand cmd1 = new SqlCommand("UPDATE EMPLOYEE_FULLADDRESS_TABLE SET PermanentAdd = #PermanentAdd, PermanentAdd2 = #PermanentAdd2, HomePlace = #HomePlace, HomeState= #HomeState, HomePin= #HomePin where EmployeeID = '" + global + "'", con);
cmd1.Parameters.AddWithValue("#PermanentAdd", TextBox1.Text);
cmd1.Parameters.AddWithValue("#PermanentAdd2", TextBox5.Text);
cmd1.Parameters.AddWithValue("#HomePlace", TextBox2.Text);
if (State.SelectedItem.Text == "--Select--")
{
State.SelectedItem.Text = TextBox3.Text;
}
cmd1.Parameters.AddWithValue("#HomeState", State.SelectedItem.Text);
cmd1.Parameters.AddWithValue("#HomePin", TextBox4.Text);
cmd1.ExecuteNonQuery();
con.Close();
lblmsg.Text = "DATA Updated Successfully";
lblmsg.ForeColor = System.Drawing.Color.Green;
}
catch (Exception exp)
{
lblmsg.Text = exp.Message;
lblmsg.ForeColor = System.Drawing.Color.Red;
}
}
// static int count = 0;
protected void EditButton_Click(object sender, EventArgs e)
{
TextBox1.Enabled = true;
TextBox2.Enabled = true;
//TextBox3.Enabled = true;
TextBox4.Enabled = true;
TextBox5.Enabled = true;
State.Enabled = true;
}
please help.
I think you have commented out your global / employeeid assignment?
// global = Session["ID"].ToString();
You should also change this to a parameter in your SQL.

Resources