《C#入门经典(中文第四版)》在程序中访问数据库学习笔记
---------------------------------------------------------------------------------------------------------
A0 ………… System.Data.SqlClient 命名空间
A1 ………… SqlConnection 类
A2 ………… SqlCommand 类
A3 ………… SqlDataReader 类
A4 ………… SqlParameter 类
※ 参考:SQLHelper 语句
A5 ………… SqlDataAdapter 类
A6 ………… System.Data 命名空间
A7 ………… DataTable 类
A8 ………… DataSet 类
A9 ………… DataTableCollection 类
G1 ………… DataRow 类
--------------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A0个 ╠══════════════════════════════════════════════════╣
╚════════╝
--------------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A1个 ╠══════════════════════════════════════════════════╣
╚════════╝
1. 表示 SQL Server 数据库的一个打开的连接。无法继承此类。
2.SqlConnection 属性:
3. SqlConnection 方法:
--------------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A2个 ╠══════════════════════════════════════════════════╣
╚════════╝
1. 表示要对 SQL Server 数据库执行的一个 Transact-SQL 语句或存储过程。无法继承此类。
2. SqlCommand 构造函数:
3. SqlCommand 属性:
SqlCommand cmd = new SqlCommand("login", conn);
cmd.CommandType = CommandType.StoredProcedure; //这里采用存储过程
cmd.CommandText = "select * from Table1 where UserName = @UserName";
cmd.Parameters.AddWithValue("UserName", textBox1.Text);
4. SqlCommand 方法:
Console.WriteLine("请输入用户名:");
string username = Console.ReadLine();
Console.WriteLine("请输入密码:");
string password = Console.ReadLine();
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Insert into T_Users3(UserName,PassWord) values('" + username + "','" + password + "')";
cmd.ExecuteNonQuery();
Console.WriteLine("插入成功!");
Console.WriteLine("影响行数为:{0}行!",cmd.ExecuteNonQuery()); //返回值为int
}
}
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "Insert into T_Users3(UserName,PassWord) output inserted.Id values('admin','888888')"; //加入了 output inserted.Id 之后会返回最后插入的Id
int i = Convert.ToInt32(cmd.ExecuteScalar());
Console.WriteLine("插入成功!");
Console.WriteLine("刚插入的为第{0}行!",i);
}
}
※ 参考:http://hi.baidu.com/asdfhxc/blog/item/3f0d95ad5d3966004a36d6bd.html
※ 参考:http://hi.baidu.com/asdfhxc/blog/item/c5ddcf6060eb974deaf8f8bf.html
--------------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A3个 ╠══════════════════════════════════════════════════╣
╚════════╝
1. 提供一种从 SQL Server 数据库读取行的只进流的方式。无法继承此类。【适合大数据量,每次传入一行数据】
2. SqlDataReader 属性:
3. SqlDataReader 方法:
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from T_Users3";
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read()) //一条条地往下执行
{
if (reader.GetString(1)[0] < 'z' && reader.GetString(1)[0] > 'A') //简单判断以字母开头的UserName
{
Console.WriteLine(reader.GetInt32(reader.GetOrdinal("Id")).ToString().PadRight(5) +
reader.GetString(reader.GetOrdinal("UserName")).Trim().PadRight(15) +
reader.GetString(reader.GetOrdinal("PassWord")).PadRight(20)); //通过PadRight,用空格将右侧补齐
}
}
}
}
}
效果如下图所示:
//通过上面四个类,建立了一个验证密码的控制台程序!Check it out!!!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string dataDir = AppDomain.CurrentDomain.BaseDirectory; //vs内嵌数据库,需加入此语句!
if (dataDir.EndsWith(@"\bin\Debug\") ||dataDir.EndsWith(@"\bin\Release\"))
{
dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
AppDomain.CurrentDomain.SetData("DataDirectory",dataDir);
}
Console.WriteLine("请输入用户名:"); //先建立数据库,并加入测试的UserName和PassWord列!
string username = Console.ReadLine();
Console.WriteLine("请输入密码:");
string password = Console.ReadLine();
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;
AttachDBFilename=|DataDirectory|\Database2.mdf;
Integrated Security=True;
User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from T_Users where UserName = '" + username + "'"; //注意这个地方的单引号,很容易出错的!
using (SqlDataReader reader = cmd.ExecuteReader()) //查找上面的username!
{
if (reader.Read()) //存在则为true
{
//用户名存在
string dbpassword = reader.GetString(reader.GetOrdinal("PassWord")); //在PassWord列中遍历
if (password == dbpassword.Trim()) //注意要去掉数据库中字符串的空格,默认有空格的!
{
Console.WriteLine("登陆成功!");
}
else
{
Console.WriteLine("登录失败!");
}
}
else
{
Console.WriteLine("用户名错误!");
}
}
}
}
Console.ReadKey();
}
}
}
//简单变形,达到上面的效果!
Console.WriteLine("输入用户名:");
string username = Console.ReadLine();
Console.WriteLine("输入密码:");
string password = Console.ReadLine();
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select count(*) from T_Users3 where UserName = '" + username + "' and PassWord = '" + password + "'"; //用户名正确,密码可以用:”3' or '1' = '1“,也可以登录成功!
int i = Convert.ToInt32(cmd.ExecuteScalar());
if (i > 0)
Console.WriteLine("Login Succeed!");
else
Console.WriteLine("Login Failed!");
}
}
//用 SqlCommand 类的 Parameters 属性改写!
Console.WriteLine("输入用户名:");
string username = Console.ReadLine();
Console.WriteLine("输入密码:");
string password = Console.ReadLine();
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select count(*) from T_Users3 where UserName = @UserName and PassWord = @PassWord";
cmd.Parameters.AddWithValue("UserName", username);
cmd.Parameters.AddWithValue("PassWord", password);
int i = Convert.ToInt32(cmd.ExecuteScalar());
if (i > 0)
Console.WriteLine("Login Succeed!");
else
Console.WriteLine("Login Failed!");
}
}
--------------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A4个 ╠══════════════════════════════════════════════════╣
╚════════╝
1. 表示 SqlCommand 的参数,也可以是它到 DataSet 列的映射。无法继承此类。
2. SqlParameter 构造函数:
首先,新建一个 SQLHelper 类:
class SQLHelper
{
public static int ExecuteNonQuery(string sql, params SqlParameter[] parameters) //执行查询
{
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
foreach(SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
return cmd.ExecuteNonQuery();
}
}
}
public static object ExecuteScalar(string sql, params SqlParameter[] parameters) //执行返回第一行第一列的内容
{
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
foreach (SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
return cmd.ExecuteScalar();
}
}
}
public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parameters) //执行返回内存中的表格
{
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
foreach (SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
DataSet dataset = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dataset);
DataTable table = dataset.Tables[0];
return table;
}
}
}
}
然后,在程序中可以按照如下来调用,参数的个数可以从1个到无数个!
private void button2_Click(object sender, EventArgs e)
{
SQLHelper.ExecuteNonQuery("insert into Table1(UserName,PassWord) values(@UserName,@PassWord)",
new SqlParameter("UserName", textBox1.Text), new SqlParameter("PassWord", textBox2.Text));
//实现数据的插入
}
private void button3_Click(object sender, EventArgs e)
{
SQLHelper.ExecuteNonQuery("update Table1 set UserName = 'Mike',PassWord = 'love' where UserName = @UserName",
new SqlParameter("UserName",textBox1.Text));
//实现数据的更新
}
private void button4_Click(object sender, EventArgs e)
{
DataTable table = SQLHelper.ExecuteDataTable("select * from Table1");
for (int i = 0; i < table.Rows.Count;i++ )
{
DataRow row = table.Rows[i];
MessageBox.Show(row["UserName"].ToString());
//实现表格存储到内存
}
}
--------------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A5个 ╠══════════════════════════════════════════════════╣
╚════════╝
1. 表示用于填充 DataSet 和更新 SQL Server 数据库的一组数据命令和一个数据库连接。无法继承此类。
2. SqlDataAdapter 构造函数:
3. SqlDataAdapter 属性:
4. SqlDataAdapter 方法:
--------------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A6个 ╠══════════════════════════════════════════════════╣
╚════════╝
1. 自动生成单表命令,用于将对 DataSet 所做的更改与关联的 SQL Server 数据库的更改相协调。无法继承此类。
2. SqlCommandBuilder 构造函数:
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from Table1";
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
DataTable table = dataset.Tables[0];
DataRow row = table.Rows[0];
row["Name"] = "Matthew";
SqlCommandBuilder builder = new SqlCommandBuilder(adapter); //传入数据库
adapter.Update(dataset);
MessageBox.Show("修改成功!");
}
}
--------------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A7个 ╠══════════════════════════════════════════════════╣
╚════════╝
--------------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A7个 ╠══════════════════════════════════════════════════╣
╚════════╝
1. 表示一个内存中数据表
2. DataTable 属性:
3. DataTable 方法:
--------------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A8个 ╠══════════════════════════════════════════════════╣
╚════════╝
1. 表示数据的内存中缓存。【适合小数据量的适合用,一次将所有放入内存】
2. DataSet 属性:
3. DataSet 方法:
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from Table1";
DataSet dataset = new DataSet(); //相当于容器
SqlDataAdapter adapter = new SqlDataAdapter(cmd); //执行SQL语句
adapter.Fill(dataset); //传入数据
DataTable table = dataset.Tables[0]; //传给Table
for (int i = 0; i < table.Rows.Count;i++ ) //遍历Table的Row
{
DataRow row = table.Rows[i]; //传递给每个Row
string name = Convert.ToString(row["UserName"]); //取值
MessageBox.Show(name);
}
}
}
--------------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第A9个 ╠══════════════════════════════════════════════════╣
╚════════╝
1. 表示 DataSet 的表的集合。
2. DataTableCollection 属性:
3. DataTableCollection 方法:
--------------------------------------------------------------------------------------------------------------
╔════════╗
╠════╣ 第G1个 ╠══════════════════════════════════════════════════╣
╚════════╝
1. 表示 DataTable 中的一行数据。
2. DataRow 属性:
3. DataRow 方法: