c#连接数据库ado.net

这是我们学校假期培训期间的课程

第一次授课由赵学臣la老师讲授 

主要内容就是数据库的设计及在c#中连接数据库的方式

数据库之前已经系统的学习过,所以就直接放一下连接数据库的部分

下面的是User1表

起初我将其定义为User 但是和数据库中的关键词可能有冲突

因此改了个名(不改也有方法)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建应用程序与数据库的通道(连接字符串)
            SqlConnection conn = new SqlConnection("Data Source = 10.33.83.56;Initial Catalog=TIM;Persist Security Info=True;User ID=sa;Password=123");
            conn.Open();
            //对数据库的添加操作
            SqlCommand cmd = new SqlCommand("SELECT * FROM User1",conn );
            //雇佣一个搬运工,去数据库拉货物
            SqlDataAdapter adpter = new SqlDataAdapter(cmd);
            //搬运工开始从数据库搬来数据
            DataSet ds = new DataSet();
            adpter.Fill(ds);
            DataTable dt = ds.Tables[0];
            foreach (DataRow row in dt.Rows)
            {
                Console.WriteLine("登录用户名:{0}\t登录密码:{1}\t真实姓名:{2}",row["Username"].ToString(), row["Password"].ToString(), row["Realname"].ToString());
            }

            conn.Close();
            Console.ReadKey();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/sdwujk160507140150/article/details/81235494