In asp.net, use C # to connect to SQL database, and use SQL statement query, never contacted C # before, recently used, groping for two days finally run up, Mark, don't like to spray
There are two ways: (the first method is not safe, I am not sure ^_^)
The first of these methods:
Copy Code code as follows:
Create a asp.net Web application, add code directly to the Page_Load function, it looks like you can use the
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 more safe than trouble .
Copy Code code as follows:
1, modify the Web.config configuration file
<configuration>
<connectionStrings>
</connectionStrings>
The following three lines are added, that is, the information connected to the database
<appSettings>
<add key= "Connect" value= "server=.; Database=northwind;uid=sa;pwd=sa; " />
</appSettings>
<system.web>
2, connect the database
Scon = configurationmanager.appsettings["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 function
Public SqlDataReader Excutedatareader (string strtxt, CommandType cmdtype, sqlparameter[] Params)
{
SqlDataReader dr = null;
if (Con. state = = connectionstate.closed)
{
Response.Write ("Database connection not open!") ");
Return Dr;
}
SqlCommand cmd = new SqlCommand ();
Cmd. Connection = con;
Cmd.commandtext = Strtxt;
Cmd.commandtype = Cmdtype;
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 inquiry
SQL statement, id=n ' id ', plus N to recognize Chinese characters.
string s = "SELECT * from table where id=n '" + ID + "'";
sqlparameter[] Params1 = null;
Save Results
SqlDataReader select_result = null;
Select_result = A.excutedatareader (S, CommandType.Text, PARAMS1);
string ss = "";
while (Select_result. Read ())
{
Write according to your own field number
SS = SS + "first field:" + select_result[0] + ", second field:" + select_result[1] + ";";
}
Test output
Response.Write (ss);