简体   繁体   中英

Username Parameter In Sql Script c# Web Project Visual Studio

I have a grid view in a web application in visual studio with a sql query attached to it. How do i pass the Username the person has logged in with into a parameter in the query

You need to insert the user's input as a variable into the SQL Query using command.Parameters.AddWithValue(). Quick Example..

var command = new SqlCommand("INSERT INTO Users (Username) VALUES (@Username)");

command.Parameters.AddWithValue("@Username", txtUsername.Text);

command.ExecuteNonQuery();

You get the username the user is logged in with (in Windows) by executing:

String userName = Environment.UserName;

In your SQL query, you would use this variable like this:

String SQLQuery = "SELECT * FROM [YourTable] WHERE colUserName = '" + userName + "';";

If you are looking for the username the person is logged into SQL-Server with (for example) you would use:

SELECT system_user;

to get:

String SQLQuery = "SELECT * FROM [YourTable] WHERE colUserName = system_user;";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM