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();
}
}
Related
Here is my SQL query:
CREATE PROCEDURE User_CRUD
#Action varchar(20),
#eno int,
#ename varchar(50),
#salary money
AS
IF #Action = 'Insert'
BEGIN
INSERT INTO employee (eno, ename, salary)
VALUES (#eno, #ename, #salary)
END
ELSE IF #Action = 'Update'
BEGIN
UPDATE employee
SET ename = #ename, salary = #salary
WHERE eno = #eno
END
ELSE IF #Action = 'Delete'
BEGIN
DELETE FROM employee
WHERE eno =#eno
END
ELSE IF #Action = 'Getemp'
BEGIN
SELECT *
FROM employee
END
ELSE IF #Action = 'Search'
BEGIN
SELECT ename, salary
FROM employee
WHERE eno = #eno
END
And here is my DAL class file:
public int AddEmployee(Models.Employee e1)
{
con.Open();
SqlCommand cmd = new SqlCommand("User_CRUD", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "Insert");
cmd.Parameters.AddWithValue("#eno", e1.Eno);
cmd.Parameters.AddWithValue("#ename", e1.Ename);
cmd.Parameters.AddWithValue("#salary", e1.Salary);
e1.RollNo = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
return e1.RollNo;
}
public int DeleteEmployee(Models.Employee e1)
{
con.Open();
SqlCommand cmd = new SqlCommand("User_CRUD", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "Delete");
cmd.Parameters.AddWithValue("#eno",e1.Eno);
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
public int UpdateEmployee(Models.Employee e1)
{
con.Open();
SqlCommand cmd = new SqlCommand("User_CRUD", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "Update");
cmd.Parameters.AddWithValue("#eno", e1.Eno);
cmd.Parameters.AddWithValue("#ename", e1.Ename);
cmd.Parameters.AddWithValue("#salary", e1.Salary);
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
public List<Models.Employee> GetEmployee()
{
List<Models.Employee> li = new List<Models.Employee>();
con.Open();
SqlCommand cmd = new SqlCommand("User_CRUD", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while(dr.Read())
{
Models.Employee e1= new Models.Employee();
e1.RollNo = int.Parse(dr[0].ToString());
e1.Eno = int.Parse(dr[1].ToString());
e1.Ename = dr[2].ToString();
e1.Salary = double.Parse(dr[3].ToString());
cmd.Parameters.AddWithValue("#Action", "Getemp");
li.Add(e1);
}
}
return li;
}
public Models.Employee SearchEmp(Models.Employee e1)
{
con.Open();
SqlCommand cmd = new SqlCommand("User_CRUD", con);
cmd.CommandType= CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "Search");
cmd.Parameters.AddWithValue("#eno", e1.Eno);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (dr.Read())
{
e1.Ename= dr[0].ToString();
e1.Salary= double.Parse(dr[1].ToString());
}
}
con.Close();
return e1;
}
When I try to perform some crud operation using single procedure it is showing error in GetEmployee() method like #Action method which was not supplied. SearchEmp() method is also showing the same error.
Can anyone help me with this?
Thanks in advance
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();
}
}
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.
I don't understand it. This code should work, but there must be something I've done wrong.
Can anyone see what I've done wrong?
string username = tbNewUSER.Text.Trim();
string password = tbNewPass.Text.Trim();
string role = "USER";
string str = "insert into UserValidation (USERNAME, PASSWORD, ROLE) values ('" + username + "','" + password + "','" + role + "')";
MessageBox.Show(username + " Registered", "User registration",MessageBoxButtons.OK, MessageBoxIcon.Information);
clsDB.InsUpDel(str);
And this is the follow up:
public static int InsUpDel(string str)
{
if (!(conn.State == ConnectionState.Open))
conn.Open(); //open connection if closed
int numRows = 0; //counter that checks number of rows affected in the db
try
{
SqlCommand cmd = new SqlCommand(str, conn);
numRows = cmd.ExecuteNonQuery();
cmd = null;
}
catch (SqlException ex)
{
string errorMsg = ex.Message; //more code can be put here
}
if (conn.State == ConnectionState.Open)
conn.Close();
return numRows;
}
Thank you.
Side notes:
Always use parameters for your queries and never string concatenation. For fun see Bobby Tables
Do not use static, there are not many places you need this.
Dont share database connections, create them and destroy them as needed.
Do not store passwords as plain text ever!
Do not catch exceptions you do not plan to handle. Log them and rethrow (using throw;) or do not catch at all. This last one will help you figure out why "its not working"
Updated code
public void UpdateUser() {
var userModel = new UserModel {
Username = tbNewUSER.Text.Trim(),
Password = tbNewPass.Text.Trim(),
Role = "USER"
};
var result = UpdateUser(userModel);
}
public int UpdateUser(UserModel user)
{
const string str = "insert into UserValidation (USERNAME, PASSWORD, ROLE) values (#userName, #password, #role)";
using(var conn = new SqlConnection("your connection string here, hint best to get it from the app.config"))
using(var command = new SqlCommand(str, conn))
{
command.Parameters.Add(new SqlParameter("#userName", SqlDbType.VarChar, 255) {Value = user.UserName});
command.Parameters.Add(new SqlParameter("#password", SqlDbType.VarChar, 255) {Value = user.Password});
command.Parameters.Add(new SqlParameter("#role", SqlDbType.VarChar, 255) {Value = user.Role});
conn.Open();
return cmd.ExecuteNonQuery();
}
}
UserModel.cs
public class UserModel {
public string UserName {get;set;}
public string Password {get;set;}
public string Role {get;set;}
}
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