方式1:

using System.Data.SqlClient;

 

string strcon,strsql;

 private void button1_Click(object sender, EventArgs e){

strcon="Server=.;Database=asdqwe;User id='sa';password='123456'";

strsql="select * from asdqwe";

SqlConnection mycon=new SqlConnection(strcon);

SqlDataAdapter mydapter=new SqlDataAdapter(strsql,mycon);

DataSet myds=new DataSet();

mydapter.Fill(myds,"DS");

dataGridView1.DataSourse=myds.Tables["DS"];

}

过程与运行:

C# 连接数据库C# 连接数据库

===============================================================================

方式2:

using System.Data.SqlClient;

 

 private void button1_Click(object sender, EventArgs e)
        {       
            string name = this.textBox1.Text;
            string password = this.textBox2.Text;
            string con = "Data Source=.;Initial Catalog=asdqwe;Integrated Security=True";//“source=.”指本机sql服务器,asdqwe:访问的数据库名
            SqlConnection connection=new SqlConnection(con);
            string sql = string.Format("select * from asdqwe where name='{0}' and password='{1}'",name,password);
            try
            {    connection.Open();
            SqlCommand command=new SqlCommand(sql, connection);
            int num = Convert.ToInt32(command.ExecuteScalar());
           
                if (num > 0)
                {
                    MessageBox.Show("登录成功");
                }
                else {MessageBox.Show("登录失败!");}
            }
            catch (Exception ex)
            {
                MessageBox.Show("登录失败" + ex);
            }
            finally
            {
                connection.Close();
            }
        }

 过程与运行:

C# 连接数据库

==============================================================================================

string strconn = "Data Source=xxx;user id=sa;pwd=;initial catalog=gltest";
SqlConnection Conn = new SqlConnection(strconn);

Conn.Open();
string sql = "insert into users(name,pwd) values (@name,@pwd)";
SqlCommand cmd =
new SqlCommand(sql, Conn);

cmd.Parameters.Add(new SqlParameter("@name", SqlDbType.NVarChar, 50));
cmd.Parameters.Add(new SqlParameter("@pwd", SqlDbType.NVarChar, 50));

cmd.Parameters["@name"].Value = this.TextBox1.Text;

cmd.Parameters["@pwd"].Value = this.TextBox2.Text;

cmd.ExecuteNonQuery();

Conn.Close();

相关文章: