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;namespace 连接数据库
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == " ")
            {
                MessageBox.Show("请输入要连接的数据库名称");
            }
            else
            {
                try
                {
                    string ConStr = "server=;database=" + textBox1.Text.Trim() + ";uid=sa;pwd=";
                    SqlConnection conn = new SqlConnection(ConStr);
                    conn.Open();
                    if (conn.State == ConnectionState.Open)
                    {
                        label2.Text = "数据库 [" + textBox1.Text.Trim() + "]已经连接并打开";
                    }
                }
                catch
                {
                    MessageBox.Show("数据连接失败");
                }
            }
        }
    }
}
各位高手,这是我写的连接数据库的代码!为什么我连接SQL server 连接不上, 我创建了数据库!就是连不上!我的SQL server的版本是2005的,VS的版本是2008的!

解决方案 »

  1.   

    server=(local)orserver=.or server=pcNameorserver=ip
      

  2.   

    有以下原因:
    1.确认数据库存在SA用户,且其密码为""
    2.server=;应改为:server=.;或server=ip(IP地址)
    3.确认连接字符串其它为正常.
      

  3.   

    给你一个我正确使用过的:private string m_strCn = "Data Source=(local);Initial Catalog=LineMonitor;Integrated Security=SSPI;uid=sa;pwd=";
      

  4.   

    主要的问题在这里
    string ConStr = "server=;database=" + textBox1.Text.Trim() + ";uid=sa;pwd=";
    server代表是服务器,如是要是本机的话就server=localhost;或者server=.;
    pwd代表密码,要正确。
      

  5.   

    Data Source=服务器IP比如(192.168.18.254);Initial Catalog=数据库名字;Persist Security Info=True;User ID=服务器数据库登录用户名;Pwd=服务器数据库登录密码