ASP.NET Tutorial/ADO.net Database/SqlServer
Содержание
- 1 Connect to SQL server with integrated Authentication or SQL Authentication
- 2 Execute delete command with SqlCommand against SqlServer
- 3 For example, the following connection string enables you to connect to a Server database named MyData:
- 4 Handle table relationship (C#)
- 5 Insert, update and delete (C#)
- 6 Read data from SQL server and fill asp:dropdownlist (C#)
- 7 You can connect to a Local database named MyLocalData.mdf by using the following connection string:
- 8 You use SQLCMD by opening a command prompt and connecting to your database with the following command:
Connect to SQL server with integrated Authentication or SQL Authentication
File: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="ConnectionTester" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton id="optSQL"
runat="server"
Text="Use SQL Authentication (with sa account)"
GroupName="Authentication"
></asp:RadioButton>
<br />
<asp:RadioButton id="optWindows"
runat="server"
Text="Use Windows Integrated Authentication"
GroupName="Authentication"
Checked="True"></asp:RadioButton>
<br />
<br />
<asp:button id="cmdConnect"
runat="server"
Text="Connect"
onclick="cmdConnect_Click"></asp:button>
<br />
<br />
<asp:label id="lblInfo" runat="server"></asp:label>
</div>
</form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Data.SqlClient;
public partial class ConnectionTester : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdConnect_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=Pubs;";
if (optWindows.Checked)
{
connectionString += "Integrated Security=SSPI";
}
else
{
connectionString += "User ID=sa";
}
SqlConnection myConnection = new SqlConnection(connectionString);
try
{
myConnection.Open();
lblInfo.Text = "<b>Server Version:</b> " + myConnection.ServerVersion;
lblInfo.Text += "<br /><b>Connection Is:</b> " + myConnection.State.ToString();
}
catch (Exception err)
{
lblInfo.Text = "Error reading the database. ";
lblInfo.Text += err.Message;
}
finally
{
myConnection.Close();
lblInfo.Text += "<br /><b>Now Connection Is:</b> ";
lblInfo.Text += myConnection.State.ToString();
}
}
}
Execute delete command with SqlCommand against SqlServer
<%@ Page Language="C#" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.SqlClient" %>
<script runat="server">
void Page_Load(object sender, EventArgs e) {
string ConnectionString = ConfigurationSettings.AppSettings["MSDEConnectString"];
SqlConnection myConnection = new SqlConnection(ConnectionString);
try{
string CommandText = "DELETE FROM Publisher WHERE PublisherID = 6";
SqlCommand myCommand = new SqlCommand(CommandText, myConnection);
myConnection.Open();
lblRecords.Text = Convert.ToString(myCommand.ExecuteNonQuery());
} catch (Exception ex){
throw(ex);
} finally{
myConnection.Close();
}
}
</script>
<html>
<head>
</head>
<body>
<form runat="server">
Records affected: <asp:Label id="lblRecords" runat="server"></asp:Label>
</form>
</body>
</html>
File: Web.config
<configuration>
<appSettings>
<add key="MSDEConnectString" value="server=(local)\YourDatabaseAddress;database=Books;uid=YourID;pwd=letmein;" />
</appSettings>
</configuration>
For example, the following connection string enables you to connect to a Server database named MyData:
Data Source=.\SQLExpress;Initial Catalog=MyData;Integrated Security=True
Handle table relationship (C#)
File: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="TableRelationships" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblList" runat="server" EnableViewState="False"></asp:Label>
</div>
</form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class TableRelationships : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
CreateList();
}
}
private string connectionString = WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;
private void CreateList()
{
string selectSQL = "SELECT au_lname, au_fname, au_id FROM Authors";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dsPubs = new DataSet();
try
{
con.Open();
adapter.Fill(dsPubs, "Authors");
cmd.rumandText = "SELECT au_id, title_id FROM TitleAuthor";
adapter.Fill(dsPubs, "TitleAuthor");
cmd.rumandText = "SELECT title_id, title FROM Titles";
adapter.Fill(dsPubs, "Titles");
}
catch (Exception err)
{
lblList.Text = "Error reading list of names. ";
lblList.Text += err.Message;
}
finally
{
con.Close();
}
DataRelation Titles_TitleAuthor = new DataRelation("Titles_TitleAuthor",dsPubs.Tables["Titles"].Columns["title_id"],dsPubs.Tables["TitleAuthor"].Columns["title_id"]);
DataRelation Authors_TitleAuthor = new DataRelation("Authors_TitleAuthor",dsPubs.Tables["Authors"].Columns["au_id"],dsPubs.Tables["TitleAuthor"].Columns["au_id"]);
dsPubs.Relations.Add(Titles_TitleAuthor);
dsPubs.Relations.Add(Authors_TitleAuthor);
foreach (DataRow rowAuthor in dsPubs.Tables["Authors"].Rows)
{
lblList.Text += "<br /><b>" + rowAuthor["au_fname"];
lblList.Text += " " + rowAuthor["au_lname"] + "</b><br />";
foreach (DataRow rowTitleAuthor in
rowAuthor.GetChildRows(Authors_TitleAuthor))
{
foreach (DataRow rowTitle in
rowTitleAuthor.GetParentRows(Titles_TitleAuthor))
{
lblList.Text += " ";
lblList.Text += rowTitle["title"] + "<br />";
}
}
}
}
}
File: Web.config
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="Pubs" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=Pubs;Integrated Security=SSPI"/>
</connectionStrings>
</configuration>
Insert, update and delete (C#)
File: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="AuthorManager" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<br />
<asp:Label id="Label1" runat="server">Select Author:</asp:Label>
<asp:DropDownList id="lstAuthor" runat="server" AutoPostBack="True" onselectedindexchanged="lstAuthor_SelectedIndexChanged"></asp:DropDownList>
<asp:Button id="cmdUpdate" runat="server" Text="Update" onclick="cmdUpdate_Click"></asp:Button>
<asp:Button id="cmdDelete" runat="server" Text="Delete" onclick="cmdDelete_Click"></asp:Button>
<br />
<asp:Label id="Label11" runat="server" Width="99px" Height="19px">Or:</asp:Label>
<asp:Button id="cmdNew" runat="server" Width="91px" Height="24px" Text="Create New" onclick="cmdNew_Click"></asp:Button>
<asp:Button id="cmdInsert" runat="server" Width="85px" Height="24px" Text="Insert New" onclick="cmdInsert_Click"></asp:Button>
</div>
<br />
<div>
<asp:Label id="Label10" runat="server" Width="100px">Unique ID:</asp:Label>
<asp:TextBox id="txtID" runat="server" Width="184px"></asp:TextBox>
(required: ###-##-#### form)<br />
<asp:Label id="Label2" runat="server" Width="100px">First Name:</asp:Label>
<asp:TextBox id="txtFirstName" runat="server" Width="184px"></asp:TextBox><br />
<asp:Label id="Label3" runat="server" Width="100px">Last Name:</asp:Label>
<asp:TextBox id="txtLastName" runat="server" Width="183px"></asp:TextBox><br />
<asp:Label id="Label4" runat="server" Width="100px">Phone:</asp:Label>
<asp:TextBox id="txtPhone" runat="server" Width="183px"></asp:TextBox><br />
<asp:Label id="Label5" runat="server" Width="100px">Address:</asp:Label>
<asp:TextBox id="txtAddress" runat="server" Width="183px"></asp:TextBox><br />
<asp:Label id="Label6" runat="server" Width="100px">City:</asp:Label>
<asp:TextBox id="txtCity" runat="server" Width="184px"></asp:TextBox><br />
<asp:Label id="Label7" runat="server" Width="100px">State:</asp:Label>
<asp:TextBox id="txtState" runat="server" Width="184px"></asp:TextBox><br />
<asp:Label id="Label9" runat="server" Width="100px">Zip Code:</asp:Label>
<asp:TextBox id="txtZip" runat="server" Width="184px"></asp:TextBox>
(required: any five digits)<br />
<br />
<asp:Label id="Label8" runat="server" Width="93px" Height="19px">Contract:</asp:Label>
<asp:CheckBox id="chkContract" runat="server"></asp:CheckBox><br />
<br />
<asp:Label id="lblResults" runat="server" Width="575px" Height="121px" Font-Bold="True"></asp:Label>
</div>
</div>
</form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Data.SqlClient;
public partial class AuthorManager : System.Web.UI.Page
{
private string connectionString = WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
FillAuthorList();
}
}
private void FillAuthorList()
{
lstAuthor.Items.Clear();
string selectSQL = "SELECT au_lname, au_fname, au_id FROM Authors";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["au_lname"] + ", " + reader["au_fname"];
newItem.Value = reader["au_id"].ToString();
lstAuthor.Items.Add(newItem);
}
reader.Close();
}
catch (Exception err)
{
lblResults.Text = "Error reading list of names. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM Authors ";
selectSQL += "WHERE au_id="" + lstAuthor.SelectedItem.Value + """;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
txtID.Text = reader["au_id"].ToString();
txtFirstName.Text = reader["au_fname"].ToString();
txtLastName.Text = reader["au_lname"].ToString();
txtPhone.Text = reader["phone"].ToString();
txtAddress.Text = reader["address"].ToString();
txtCity.Text = reader["city"].ToString();
txtState.Text = reader["state"].ToString();
txtZip.Text = reader["zip"].ToString();
chkContract.Checked = (bool)reader["contract"];
reader.Close();
lblResults.Text = "";
}
catch (Exception err)
{
lblResults.Text = "Error getting author. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
protected void cmdNew_Click(object sender, EventArgs e)
{
txtID.Text = "";
txtFirstName.Text = "";
txtLastName.Text = "";
txtPhone.Text = "";
txtAddress.Text = "";
txtCity.Text = "";
txtState.Text = "";
txtZip.Text = "";
chkContract.Checked = false;
lblResults.Text = "Click Insert New to add the completed record.";
}
protected void cmdInsert_Click(object sender, EventArgs e)
{
if (txtID.Text == "" || txtFirstName.Text == "" || txtLastName.Text == "")
{
lblResults.Text = "Records require an ID, first name, and last name.";
return;
}
string insertSQL;
insertSQL = "INSERT INTO Authors (";
insertSQL += "au_id, au_fname, au_lname, ";
insertSQL += "phone, address, city, state, zip, contract) ";
insertSQL += "VALUES (";
insertSQL += "@au_id, @au_fname, @au_lname, ";
insertSQL += "@phone, @address, @city, @state, @zip, @contract)";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("@au_id", txtID.Text);
cmd.Parameters.AddWithValue("@au_fname", txtFirstName.Text);
cmd.Parameters.AddWithValue("@au_Lname", txtLastName.Text);
cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Parameters.AddWithValue("@city", txtCity.Text);
cmd.Parameters.AddWithValue("@state", txtState.Text);
cmd.Parameters.AddWithValue("@zip", txtZip.Text);
cmd.Parameters.AddWithValue("@contract", Convert.ToInt16(chkContract.Checked));
int added = 0;
try
{
con.Open();
added = cmd.ExecuteNonQuery();
lblResults.Text = added.ToString() + " record inserted.";
}
catch (Exception err)
{
lblResults.Text = "Error inserting record. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
if (added > 0)
{
FillAuthorList();
}
}
protected void cmdUpdate_Click(object sender, EventArgs e)
{
string updateSQL;
updateSQL = "UPDATE Authors SET ";
updateSQL += "au_fname=@au_fname, au_lname=@au_lname, ";
updateSQL += "phone=@phone, address=@address, city=@city, state=@state, ";
updateSQL += "zip=@zip, contract=@contract ";
updateSQL += "WHERE au_id=@au_id_original";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(updateSQL, con);
cmd.Parameters.AddWithValue("@au_fname", txtFirstName.Text);
cmd.Parameters.AddWithValue("@au_Lname", txtLastName.Text);
cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Parameters.AddWithValue("@city", txtCity.Text);
cmd.Parameters.AddWithValue("@state", txtState.Text);
cmd.Parameters.AddWithValue("@zip", txtZip.Text);
cmd.Parameters.AddWithValue("@contract", Convert.ToInt16(chkContract.Checked));
cmd.Parameters.AddWithValue("@au_id_original", lstAuthor.SelectedItem.Value);
int updated = 0;
try
{
con.Open();
updated = cmd.ExecuteNonQuery();
lblResults.Text = updated.ToString() + " record updated.";
}
catch (Exception err)
{
lblResults.Text = "Error updating author. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
if (updated > 0)
{
FillAuthorList();
}
}
protected void cmdDelete_Click(object sender, EventArgs e)
{
string deleteSQL;
deleteSQL = "DELETE FROM Authors ";
deleteSQL += "WHERE au_id=@au_id";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(deleteSQL, con);
cmd.Parameters.AddWithValue("@au_id ", lstAuthor.SelectedItem.Value);
int deleted = 0;
try
{
con.Open();
deleted = cmd.ExecuteNonQuery();
lblResults.Text = "Record deleted.";
}
catch (Exception err)
{
lblResults.Text = "Error deleting author. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
if (deleted > 0)
{
FillAuthorList();
}
}
}
File: Web.config
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="Pubs" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=Pubs;Integrated Security=SSPI"/>
</connectionStrings>
</configuration>
Read data from SQL server and fill asp:dropdownlist (C#)
File: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="AuthorBrowser" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:label id="Label1"
runat="server"
Width="120px"
Height="20px">Select Author:</asp:label>
<asp:dropdownlist id="lstAuthor"
runat="server"
Width="256px"
Height="22px"
AutoPostBack="True"
onselectedindexchanged="lstAuthor_SelectedIndexChanged">
</asp:dropdownlist>
<br />
<asp:label id="lblResults" runat="server" Width="384px" Height="168px">
</asp:label>
</div>
</form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Text;
public partial class AuthorBrowser : System.Web.UI.Page
{
private string connectionString = WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
FillAuthorList();
}
}
private void FillAuthorList()
{
lstAuthor.Items.Clear();
string selectSQL = "SELECT au_lname, au_fname, au_id FROM Authors";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["au_lname"] + ", " + reader["au_fname"];
newItem.Value = reader["au_id"].ToString();
lstAuthor.Items.Add(newItem);
}
reader.Close();
}
catch (Exception err)
{
lblResults.Text = "Error reading list of names. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e)
{
string selectSQL;
selectSQL = "SELECT * FROM Authors ";
selectSQL += "WHERE au_id="" + lstAuthor.SelectedItem.Value + """;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
StringBuilder sb = new StringBuilder();
sb.Append("<b>");
sb.Append(reader["au_lname"]);
sb.Append(", ");
sb.Append(reader["au_fname"]);
sb.Append("</b><br />");
sb.Append("Phone: ");
sb.Append(reader["phone"]);
sb.Append("<br />");
sb.Append("Address: ");
sb.Append(reader["address"]);
sb.Append("<br />");
sb.Append("City: ");
sb.Append(reader["city"]);
sb.Append("<br />");
sb.Append("State: ");
sb.Append(reader["state"]);
sb.Append("<br />");
lblResults.Text = sb.ToString();
reader.Close();
}
catch (Exception err)
{
lblResults.Text = "Error getting author. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
}
File: Web.config
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="Pubs" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=Pubs;Integrated Security=SSPI"/>
</connectionStrings>
</configuration>
You can connect to a Local database named MyLocalData.mdf by using the following connection string:
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|MyLocalData.mdf;
Integrated Security=True;User Instance=True
You use SQLCMD by opening a command prompt and connecting to your database with the following command:
SQLCMD -S .\SQLExpress