How to write update stored procedure in webmatrix form? - c#

Here I write update query in my webmatrix form which run correctly but I want to use a stored procedure in place of query so how can I write that?
var UpdateQuery = "UPDATE Reg_tb SET FirstName = #0, LastName = #1, UserName = #2, Password = #3 WHERE UID = #4";
db.Execute(UpdateQuery, FirstName, LastName, UserName, Password, Userid);

Maybe this?
var execProc="EXEC ProcName FirstName=#0,LastName=#1,UserName=#2,Password=#3, UID=#4";
db.Execute(execProc,FirstName,LastName,UserName,Password,Userid);

Related

Insert Guid and retrieve value with dapper

I am trying to insert a record into my database and retrieve the GUID it just added in.
Let's say if I have a table with 3 columns, GUID, FirstName, LastName. I need to insert a new record and then get back the GUID that was just generated. The problem is that first and last name are duplicated, often. I am not quite sure how to accomplish
Here is what I tried, I know the below won't work as I am not really telling it which column to select back and I'm not sure how to tell it:
var query = #"INSERT INTO MyTable(GUID, FirstName, LastName)
SELECT
#GUID, #FirstName, #LastName);
using (var oConn = CreateConnection())
{
var test = oConn.Query<string>(query, new
{
GUID = Guid.NewGuid(),
"John",
"Doe"
}).Single();
}
The error that I get is
Sequence contains no elements
If you want only the Guid which you inserted, Why not store it in a local variable in your code and use that as needed ?
I also see some errors in your code. The below code is corrected and should work.
var guid = Guid.NewGuid();
var query = #"INSERT INTO
MyTable (GUID, FirstName, LastName) values ( #GUID, #FirstName,#LastName);";
using (var conn = CreateConnection())
{
conn.Execute(query, new { #GUID = guid, #FirstName= "John", #LastName= "Scott" });
}
// You can use the value in guid variable now. It will be Id you inserted just now
Dapper Contrib needs a Auto Generated ID, It cannot be a GUID and you cannot pass a pre generated Guid

C# return Identity on Insert

I have a problem, I need to return the identity of the record I have just created in c# and save it as an integerr.
I've seen loads of examples on the internet but I just can't seem to adapt it for what I need.
Any help appreciated
cmprawf.CommandText = "INSERT INTO profiion( // Code that inserts in the right place )";
cmprawf.ExecuteNonQuery();
cnTB.Close();
You can add a SELECT to your batch and return the newly created identifier:
cmprawf.CommandText = "INSERT INTO profiion( // Code that inserts in the right place );" +
"SELECT SCOPE_IDENTITY()";
int newID = (int)cmprawf.ExecuteScalar();
cnTB.Close();
Add SELECT SCOPE_IDENTITY to your query, then you can retrieve it via ExecuteScalar:
string sql = #"INSERT INTO profiion( // Code that inserts in the right place );
;SELECT CAST(scope_identity() AS int)";
cmprawf.CommandText = sql;
int newID = (int)cmprawf.ExecuteScalar();
You simply need to select the SCOPE_IDENTITY and retrieve it using ExecuteScalar.
cmprawf.CommandText = "INSERT INTO profiion( // Code that inserts in the right place ); SELECT SCOPE_IDENTITY();";
int id = cmprawf.ExecuteScalar();
cnTB.Close();
If your db is SQL Server then
cmprawf.CommandText = "INSERT INTO profiion( // Code that inserts in the right place );SELECT SCOPE_IDENTITY()";
int yourId = (int)cmprawf.ExecuteScalar();
cnTB.Close();
You can always view the last part of Microsoft's info on this if you want to use parameters(better)
http://technet.microsoft.com/en-us/library/ms190315.aspx
You can use the return value of the sql command. Every stored procedure can have a return value of type int and you can retrieve it as follows :
SqlParameter returnParameter = cmd.Parameters.Add("RetVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int id = (int) returnParameter.Value;
code is copied from this post's second answer :
Get Return Value from Stored procedure in asp.net
Also In your stored procedure you can get the id of the inserted row by calling the SCOPE_IDENTITY() function .

Ms Access password Storage

I am using MS Access as a database for a school project. The following is my query:
public static string qry4 = "update INTERNETSETTINGS set password = #password , url = #url , databasename = #databasename , port = #port , username = #username";
It is giving me the following error: Syntax Error in Update Statement
Command.Parameters.AddWithValue("#url", urlBox.Text.ToString());
Command.Parameters.AddWithValue("#databasename", databaseBox.Text.ToString());
Command.Parameters.AddWithValue("#port", portBox.Text.ToString());
Command.Parameters.AddWithValue("#username", userBox.Text.ToString());
Command.Parameters.AddWithValue("#password", passwordBox.Text.ToString());
It is making me angry because every thing is ok and right on target but still I am getting the error, but when I remove password from query it works fine. Please Help.
Most likely, password is a reserved keyword. Place it in braces...
update INTERNETSETTINGS set [password] = #password...

MVC4 and Entity Framework 5 stored procedures

Hi Im trying to access a database table in my mvc4 application using a stored procedure and Entity Framework 5.
I created a FormValueModel.edmx file and imported the User Table and the GetUser Stored Procedure
Here is the code for the GetUser Stored Procedure
SELECT
*
FROM
[User].[User]
Where
#UserName = UserName
AND #UserPassword = UserPassword
AND Active = 1
Here is the code in my Controller to access the stored procedure
using (var db = new FormValueEntities())
{
string userName ="TestUser"
string password = "Password"
var query = db.GetUser(userName, password);
}
Why cant I access the table by using query.UserName or query.UserPassword ect.
Thanks in advance
You need to take the first item from the query i.e.
var user = db.GetUser(userName, password).SingleOrDefault();
you need to do something like this:
var query = (from a in db.GetUser(userName, password)
select new User
{
UserName =a.UserName
...other fields
}).tolist();
Check the Stored Procedure!!!
SELECT
*
FROM
[User].[User]
Where
#UserName = UserName
AND #UserPassword = UserPassword
AND Active = 1
Good:
SELECT
*
FROM
[User].[User]
Where
UserName = #UserName
AND UserPassword = #UserPassword
AND Active = 1

Verify SQL has executed correctly in WebMatrix/Razor?

I am trying to verify if my SQL has been executed correctly, and if not return an error.
My code :
var db = Database.Open("database");
db.Execute("INSERT INTO Users(Username, Email, FirstName, SecondName) VALUES(?,?,?,?)", username, email, firstName, secondName);
Also, how can you mark a column as unique using WebMatrix? This seems to be a pretty basic functionality that I am really missing! I want to make it so that emails and usernames must be unique, but I cannot see any way to do this? I am essentially then hoping to test if the INSERT INTO can be executed (i.e there is no email/username the same already existing in the database).
Thank you for the help.
For your first question:
The Execute method returns the number of affected records, and your code snip is doing an insert so if it fails it'll return a value that isn't equal to 1.
var db = Database.Open("database");
if (db.Execute("INSERT INTO Users(Username, Email, FirstName, SecondName) VALUES(?,?,?,?)", username, email, firstName, secondName) < 1)
throw new Exception("Wasn't able to insert User record");
The second, I'm not sure about but it should probably be asked in a separate question.
I would create a stored procedure that conditionally adds the new user and returns a row count (0 if the user already exists):
create procedure dbo.AddUser
#username varchar(80)
, #email varchar(128)
, #firstname varchar(128)
, #secondname varchar(128)
as
insert into [Users] (Username,Email,FirstName,SecondName)
select #username, #email, #firstname, #secondname
where not exists(
select 1 from [Users] (nolock)
where Username=#username
and Email=#email
)
return ##rowcount
go
Calling from C#:
var db = Database.Open("database");
if (db.Execute("dbo.AddUser #username=?, #email=?, #firstname=?, #secondname=?", username, email, firstName, secondName) < 1)
throw new Exception("Wasn't able to insert User record");

Categories