欢迎来到 安卓源码空间!
安卓源码空间

                                                   C#数据库操作步骤


1.建立与数据库的链接


1.1 //引入操作数据库的命令空间


在程序最上方引入操作数据库的命令空间,最后一行的Using


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;//引入操作数据库的命令空间
 


引入命令空间后就可以建立与数据库的连接了:这里有两种链接方式,具体可以参考SqlServer 的配置是Windows验证 还是 Sql Server身份验证;



在这里插入图片描述


如果是window验证:


String connectStr = "server=LAPTOP-LI0DF1DE;database=Student;Integrated Security=true";//数据库账号及密码 Windows身份验证 

SQLServer验证方式:


String connectStr = "server=自己的Server名称;database=库名;uid=数据库账号;pwd=数据库密码"; //SQL server身份验证方法 SqlConnection connect = new SqlConnection(connectStr); 


2.编写SQL语句


编写对应的SQL语句,以查询为例:


string sql = "select count(1) from UserInfo c where c.username='"+txtUserName.Text.Trim()+"' and c.userpassword='"+txtUserPassWord.Text.Trim()+"'"; 

3.创建Command对象


将SQL以及链接对象作为参数传入


SqlCommand command = new SqlCommand(sql, connect); 

4.打开链接


connect.Open(); 

5.执行命令 执行sql的前提必须满足连接是open状态


这里执行的方法有很多种,后续我再更新


object result = command.ExecuteScalar();//执行查询,并返回第一行第一列的值 

6.关闭链接


执行完操作后即可关闭连接


connect.Close(); 

7.处理结果


if (result == null || result == DBNull.Value || (int)result == 0)
            {
                MessageBox.Show("用户名或密码错误", "登录提示框", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else {
                MessageBox.Show("登录成功,正在跳转应用主界面", "登录提示框", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //转到主页面
            }
 



————————————————

                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
                        
原文链接:https://blog.csdn.net/qq_42724864/article/details/119913341

copyright@ 2020-2028  安卓源码空间网版权所有   

备案号:豫ICP备2023034476号-1号