分装一个SqlHelper类方便使用,着重理解params SqlParameters[] commandParamters

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Data.SqlClient;

using System.Configuration;

using _17DateStr.DataSet1TableAdapters;

/* DataSet

 * 每次读取的数据都创建连接,执行Command得到SqlDataReader太麻烦,让我们封装一个方法

 *

 * SqlDataReader对于小数据量的数据来说带来的只有麻烦,优点可以忽略不计

 *

 * SqlDataReader是连接相关的,SqlDataReader中的查庖结果并不是放到程序中的

 * 而是放在数据库服务器中,SqlDataReader只是相当于放了一个指针(游标),只能读取当前游标指向的行

 * 一旦连接开就不能再读取,这样做的好处就是无论查询结果有多少条,对程序占用的内存都几乎没有影响

 * ADO.Net中提供了数据集的机制,将查询结果填充到本地内存中,这样连接断开,服务器断开都不影响数据的读取

 * DataSet dataset = new DataSet();

 * SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(dataset);

 *

 * SqlDataAdapter是DataSet和数据库之间的沟通的桥梁,数据集DataSet包含若干表DataTable,DataTable包含若干行DataRow

 * foreach(DataRow row in dataset.Tables[0].Rows){

 *    row["name"];

 * }

 *

 *

 * SQLHelper

 * 封装一个SQLHelper类方便使用,提供ExecuteData Table(string sql, params SqlParameter[] parameters)

 * ExecuteNonQuery(string sql, params SqlParameter[] parameters)

 * ExecuteScalar(string sql, params SqlParameter[] parameters)

 * 等方法,网上有自由软件提供的最全的SQLHelper类,是Enterprise Libarary 中的一部分

 * 用Sqlhelper重写登陆程序

 * 用SQLHelper重写省市选择程序, 电话地址归属地查询

 * new SqlParameter("e",0)的陷阱

 * sqlconnection在程序中一直保持它open可以吗?对于数据库来说,连接是非常宝贵的资源,一定要用完了就close display

 *

 *

 * DataSet的更新

 * 可以更新row["Name"] = "yzk"; 删除行datatable.Rows.Remove(),新增行datatable.NewRow(); 这一切都是修改的内存中的DataSet,没有修改数库

 * 可以调用SqlDataAdpater的update方法将对DataSet的修改提交到数据库,Update方法有很多重载方法,可以提交整个DataSet,DataTable,或者若干DataRow

 * 但是需要为sqlDataAdapter提供DeleteCommand, UpdateCommand InsertCommand它才知道如何将对DataSet的修改提交到数据库

 * 由于这几个Command要求格式非常苛刻,因此开发人员自己写非常困难,可以用SqlCommandBuilder自动生成这几个command,用法很简单

 * new SqlCommandBuilder(adapter) 查看生成的Command(没有直接赋值给SqlDataAdapter)

 * 看SqlCommandBuilder的, sqlCommandBuilder要求表必须有主键

 * (*)通过DataRow的RowState可以获得行的状态(删除,修改,新增等);调用DataSet的GetChanges()方法得到变化的结果集,降低传递的资源占用

 *

 */

namespace _17DateStr

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)

        {

            SqlHelp.ExecuteNonQuery("Insert into T_Persons(name,age) values(@name,@age)", new SqlParameter("name","tom"),new SqlParameter("age",11));

            MessageBox.Show("插入成功!");

        }

        private void button2_Click(object sender, EventArgs e)

        {

            object i = SqlHelp.ExecuteScalar("select count(*) FROM T_Persons");

            MessageBox.Show("记录总数为:"+Convert.ToString(i));

        }

        private void button3_Click(object sender, EventArgs e)

        {

            SqlDataReader reader = SqlHelp.ExecuteReader("Select * FROM T_Persons");

            while (reader.Read())

            {

                string name = reader.GetString(reader.GetOrdinal("name"));

                MessageBox.Show("用户名为:" + name);

            }

        }

        private void button4_Click(object sender, EventArgs e)

        {

            /*string connstr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connstr))

            {

                conn.Open();

                using (SqlCommand cmd = conn.CreateCommand())

                {

                    cmd.CommandText = "select * FROM T_Persons";

                    DataSet dataset = new DataSet();

                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);

                    adapter.Fill(dataset);

                    DataTable table = dataset.Tables[0];

                    for (int i = 0; i < table.Rows.Count; i++)

                    {

                        DataRow row = table.Rows[i];

                        string name = Convert.ToString(row["name"]);

                        MessageBox.Show(name);

                    }

                }

            }*/

            DataSet dataset = new DataSet();

            string connstr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connstr))

            {

                conn.Open();

                using (SqlCommand cmd = conn.CreateCommand())

                {

                    cmd.CommandText = "select * FROM T_Persons";

                   

                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);

                    adapter.Fill(dataset);

                }

            }

            DataTable table = dataset.Tables[0];

            for (int i = 0; i < table.Rows.Count; i++)

            {

                DataRow row = table.Rows[i];

                string name = Convert.ToString(row["name"]);

                MessageBox.Show(name);

            }

        }

        private void button5_Click(object sender, EventArgs e)

        {

            DataTable table = SqlHelp.ExecuteDataTable("select * FROM T_Persons");

            foreach (DataRow row in table.Rows)

            {

                string name = Convert.ToString(row["name"]);

                MessageBox.Show(name);

            }

        }

        private void tb_login_Click(object sender, EventArgs e)

        {

            string name = tb_username.Text;

            string password = tb_password.Text;

            if (name != "" && password != "")

            {

                DataTable table = SqlHelp.ExecuteDataTable("select * FROM T_User where [email protected]", new SqlParameter("name", name));

                if (table.Rows.Count >= 1)

                {

                    DataRow row = table.Rows[0];

                    int errorTimes =Convert.ToInt32(row["errortimes"]);

                    if(errorTimes >= 3)

                    {

                        MessageBox.Show("用户被锁定,暂时不能登陆!");

                        return;

                    }else{

                        string p = Convert.ToString(row["password"]);

                        if(p == password){

                           MessageBox.Show("登陆成功!");

                           SqlHelp.ExecuteNonQuery("update T_User set errortimes=0 where [email protected]", new SqlParameter("name",name));

                           return;

                        }else{

                           

                           MessageBox.Show("登陆失败!");

                           SqlHelp.ExecuteNonQuery("update T_User set errortimes = errortimes+1 where name = @name",new SqlParameter("name",name));

                           return;

                        }

                    }

                }

                else {

                    MessageBox.Show("用户名不存在!");

                }

            }

            else {

                MessageBox.Show("用户名和密码不能为空");

            }

            

        }

        private void Form1_Load(object sender, EventArgs e)

        {

            DataTable table = SqlHelp.ExecuteDataTable("select * FROM promary");

            cb_promary.DisplayMember = "name";

            foreach (DataRow row in table.Rows)

            {

                 Promary pr = new Promary();

                 pr.id = Convert.ToInt32(row["proID"]);

                 pr.name = Convert.ToString(row["proName"]);

                 cb_promary.Items.Add(pr);

            }

        }

        private void cb_promary_SelectedIndexChanged(object sender, EventArgs e)

        {

            Promary pr = (Promary)cb_promary.SelectedItem;

            int id = pr.id;

            string name = pr.name;

            DataTable table = SqlHelp.ExecuteDataTable("select * FROM city WHERE [email protected]",new SqlParameter("proID",id));

            cb_city.Items.Clear();

            cb_city.DisplayMember = "name";

            foreach (DataRow row in table.Rows)

            {

                Promary p = new Promary();

                p.id = Convert.ToInt32(row["cityID"]);

                p.name = Convert.ToString(row["cityName"]);

                cb_city.Items.Add(p);

            }

        }

        private void button6_Click(object sender, EventArgs e)

        {

            DataTable table = SqlHelp.ExecuteDataTable("select * FROM T_User WHERE id = @id",new SqlParameter("id",(object)0));

        }

        private void button7_Click(object sender, EventArgs e)

        {

            String connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(connStr))

            {

                conn.Open();

                using (SqlCommand cmd = conn.CreateCommand())

                {

                    cmd.CommandText = "select * FROM T_Persons";

                    DataSet dataset = new DataSet();

                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);

                    adapter.Fill(dataset);

                    DataTable table = dataset.Tables[0];

                    DataRow row = table.Rows[0];

                    row["name"] = "jason"; //修改值

                    foreach (DataRow r in table.Rows)

                    {

                        string name = Convert.ToString(r["name"]);

                        MessageBox.Show("name值为:"+name);

                    }

                    //table.Rows.RemoveAt(1); //删除值

                    //table.NewRow();         //新建一个Row

                    //这里的sqlCommandBuilder主要是生成更新语句

                    SqlCommandBuilder builder = new SqlCommandBuilder(adapter);

                    

                    //这里出现了小错误,没有为表设置主键,所以提示错误

                    //"update T_Persons set [email protected], [email protected]"

                    adapter.Update(dataset);//对DataSet的修改都在内存中,没有提交到数据库

                }

            }

        }

        private void button8_Click(object sender, EventArgs e)

        {

            T_UserTableAdapter adapter = new T_UserTableAdapter();

            _17DateStr.DataSet1.T_UserDataTable data = adapter.GetData();

            for (int i = 0; i < data.Count; i++)

            {

                _17DateStr.DataSet1.T_UserRow userRow = data[i];

                MessageBox.Show(userRow.name);

            }

        }

    }

    public class Promary

    {

        public int id { get; set; }

        public string name { get; set; }

    }

}

时间: 2024-10-01 15:06:16

分装一个SqlHelper类方便使用,着重理解params SqlParameters[] commandParamters的相关文章

分装一个SqlHelper类方便使用,着重理解params Sql

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.Configuration; using _17

自学.net(1)手写一个sqlhelper类

自学.net已经快一个月了,看的是传智播客的视频,今天正好申请了博客,就先把手写的sqlhelper类上传上去吧 别忘了在解决方案管理器的“引用”添加System.Configuration 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Configuration; 6 using System.Data.SqlClient;

ASP.NET MVC 排球计分程序 (四)实体类和SqlHelper类的设计

整体解决方案的图如下: . 在Model里添加一个叫PersonA的类 public class PersonA { public int id { get; set; } public string name { get; set; } } 添加一个叫PersonB的类 public class PersonB { public int id { get; set; } public string name { get; set; } } 添加一个叫ScoreA的类 public class

分享一个简单的简单的SQLHelper类

分享一个简单的简单的SQLHelper类,代码如下: 1 class SqlHelper 2 { 3 public static readonly string connstr = 4 ConfigurationManager.ConnectionStrings["dbConnStr"].ConnectionString; 5 6 public static int ExecuteNonQuery(string cmdText, 7 params SqlParameter[] para

整理出一个比较实用的SqlHelper类 满足大多数情况的使用

/// <summary> /// SqlHelper类 by zy 2017-8-17 /// </summary> public sealed class SqlHelper { //如果项目中只连接了一个数据库 那么可以在此定义一个固定的连接字符串 private static string connectionStr = ConfigurationManager.ConnectionStrings["SQLConnString1"].Connection

强大的SQLHelper类

在做机房收费系统的时候,曾经使用过Sqlhelper,当时对此内容理解不是很好,参照的是下篇的博客: vb.net-SQLHelper类的使用 而做过之后,当再次回首往事的时候,发现这个SQLHelper类并 不是那么的强大.其实可以在多扩充些.并且不好的地方是没有加入安全的事务机制,在此小编在前人的基础上,模仿别人写了一个类似的Sqlhelper.先看下类图. 首先看一下此类,一共包含了13中方法,是对数据库增删改查的扩充,方便了用户的各种操作.比如当查询数据库的时候,可以返回DataRow.

小结在一个java源文件当中可以有多个类,但是为什么只能有一个public类呢?而当这个类被修饰为public的话,为什么源文件名必须要与类名相同呢?

Java编程思想中的一段话: 当编写一个java源代码文件时,此文件通常被称为编译单元(有时也被称为转译单元).每个编译单元都必须有一个后缀名.java,而在编译单元内则可以有一个public类,该类的名称必须与文件的名称相同(包括大小写,但不包括文件的后缀名.java).每个编译单元只能有一个public类,否则编译器就不会接受.如果在该编译单元之中还有额外的类的话,那么在包之外的世界是无法看见这些类的,这是因为它们不是public类,而且它们主要用来为主public类提供支持. 理解: 每编

设计一个Bank类,银行某账号的资金往来账管理

设计一个Bank类,实现银行某账号的资金往来账管理,包括建账号.存入.取出等.Bank类包括私有数据成员top(当前指针).date(日期).money(金额).rest(余额)和sum(累计余额).另有一个构造函数和3个成员函数bankinO(处理存入账).bankout()(处理取出账)和disp( )(出明细账). [知识点]:2.2  2.3 [参考分]:25分 [难易度]:B 实现案例: /* 2017年8月19日23:03:58 */ #include<iostream> clas

【Android开发VR实战】三.开发一个寻宝类VR游戏TreasureHunt

转载请注明出处:http://blog.csdn.net/linglongxin24/article/details/53939303 本文出自[DylanAndroid的博客] [Android开发VR实战]三.开发一个寻宝类VR游戏TreasureHunt VR即Virtual Reality虚拟现实.虚拟现实技术是一种可以创建和体验虚拟世界的计算机仿真系统它利用计算机生成一种模拟环境是一种多源信息融合的交互式的三维动态视景和实体行为的系统仿真使用户沉浸到该环境中. 那么,如何在Androi