In ASP. in. NET, use C # to connect to the SQL database and use SQL statements for queries. I have never touched C # before. I used it recently and finally ran it for two days. Mark it, dislike, not spray
There are two methods: (the first method is not safe, and I do not know ^_^)
Method 1:
Copy codeThe Code is as follows:
// Create an ASP. NET Web application and directly add the code to the Page_load function. It seems that you can use it.
Public void Page_Load (object sender, EventArgs e)
{
Using (SqlConnection con = new SqlConnection ("Data Source =.; uid = sa; pwd = sa; Database = NorthWind "))
{
String username = "forever ";
String strSQL = "select * from table where name = '" + username + "'";
SqlDataAdapter adapter = new SqlDataAdapter (strSQL, con );
DataSet ds = new DataSet ();
Adapter. Fill (ds );
Foreach (DataRowView drv in ds. Tables [0]. DefaultView)
{
Response. Write (drv ["first field"] + "|" + drv ["second field"]);
}
}
}
The second method is safer, which means it is more troublesome.
Copy codeThe Code is as follows:
// 1. Modify the Web. config configuration file
<Configuration>
<ConnectionStrings>
</ConnectionStrings>
// The following three rows are the added content, that is, the information for connecting to the database.
<Deleetask>
<Add key = "connect" value = "server =.; database = NorthWind; uid = sa; pwd = sa;"/>
</AppSettings>
<System. web>
// 2. Connect to the database
SCon = ConfigurationManager. receivettings ["connect"];
If (string. IsNullOrEmpty (sCon ))
{
Response. Write ("the connection string is empty! ");
}
Con = new SqlConnection (sCon );
// 3. Open the database
If (con. State = ConnectionState. Closed)
Con. Open ();
// 4. query Functions
Public SqlDataReader ExcuteDataReader (string strTxt, CommandType parameter type, SqlParameter [] Params)
{
SqlDataReader dr = null;
If (con. State = ConnectionState. Closed)
{
Response. Write ("the database connection is not enabled! ");
Return dr;
}
SqlCommand cmd = new SqlCommand ();
Cmd. Connection = con;
Cmd. CommandText = strTxt;
Cmd. CommandType = primitive type;
If (Params! = Null)
{
Foreach (SqlParameter param in Params)
{
If (param! = Null) cmd. Parameters. Add (param );
}
}
# If NOTALLOWEXCEPTION
Try
# Endif
{
If (cmd. ExecuteScalar ()! = Null)
{
Dr = cmd. ExecuteReader ();
}
}
# If NOTALLOWEXCEPTION
Catch (SqlException se)
{
_ ObjToShowErr = se;
_ SError = se. Message;
Return null;
}
Finally
# Endif
{
Cmd. Dispose ();
}
Return dr;
}
// 5. Execute the query
// SQL statement, id = n'id', plus N to recognize Chinese characters.
String s = "select * from table where id = N'" + id + "'";
SqlParameter [] Params1 = null;
// Save the result
SqlDataReader select_result = null;
Select_result = a. ExcuteDataReader (s, CommandType. Text, Params1 );
String ss = "";
While (select_result.Read ())
{
// Write data based on the number of fields
Ss = ss + "first field:" + select_result [0] + ", second field:" + select_result [1] + ";";
}
// Test output
Response. Write (ss );