运行错误!
使用该方法:添加-新建项-本地数据库(做好了数据表),数据库连接测试成功。但运行时出现这样的问题:
在建立与服务器的连接时出错。在连接到 SQL Server 2005 时,在默认的设置下 SQL Server 不允许进行远程连接可能会导致此失败。 (provider: 命名管道提供程序, error: 40 - 无法打开到 SQL Server 的连接)
已经在SQL的外围配置设置中把他的远程连接设置为TCP/IP和named pipes同时允许,只使用tcp/ip也尝试过同样出现这样的错误!已经重新启动数据库引擎服务后,对连接设置所做的更改才会生效。
这是我的代码:(界面是一个Button按钮,和一个listview控件)
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 WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
SqlConnection conn;
private void button1_Click(object sender, EventArgs e)
{
conn = new SqlConnection("server=.;database=Database1;uid=sa;pwd=");
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from kk";
cmd.CommandType = CommandType.Text;
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
listView1.Items.Add(sdr[1].ToString());
}
conn.Dispose();
button1.Enabled = false;
}
}
}