-3

感谢一些帮助,我解决了我以前的一些问题,但是当我单击注册按钮(button1)时,我收到以下错误:

ERROR = ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Odbc;


public partial class CompanyLogin : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
    OdbcConnection conn = new OdbcConnection();
    conn.ConnectionString = @".\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\VCtemps.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";

    string sql = "insert into company values(@CompName, @BusinessType, @Pword)";
    OdbcCommand cmd = new OdbcCommand(sql);
    string CompName = txtCompName.Text;
    string BusinessType = DropDownList1.Text;
    string Pword = txtPassword.Text;
    conn.Open();
    cmd.Connection = conn;

    cmd.CommandText = "insert into company(CompName, BusinessType, Pword) Values(@CompName,@BusinessType,@Pword);";
    cmd.Parameters.AddWithValue("@CompName",SqlDbType.VarChar);    
    cmd.Parameters.AddWithValue("@BusinessType",SqlDbType.VarChar);    
    cmd.Parameters.AddWithValue("@Pword",SqlDbType.VarChar);    

cmd.ExecuteNonQuery();

    conn.Close();

    txtCompName.Text = "";
    txtPassword.Text = "";
    DropDownList1.Text = "";
}
}
4

2 回答 2

2

非常不言自明的错误消息。您需要在连接字符串中指定数据源和驱动程序。访问数据库的连接字符串以查找您所针对的数据库的连接字符串应该是什么样子。

于 2012-10-11T15:02:44.697 回答
0

在您的连接字符串中,您已经转义了黑斜线,并且您在字符串前面使用了 @ 符号。可能问题是你已经做到了。删除 @ 或删除两个位置的双斜杠。

@".\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\VCtemps.mdf...etc

...但老实说,你不应该像那样硬编码你的连接字符串。您应该将连接字符串添加到 web.config 文件的 ConnectionStrings 部分:

<configuration>
    <connectionStrings>
       <add name="ConnectionString" connectionString=".\SQLEXPRESS;AttachDbFilename=|DataDirectory|\VCtemps.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True" />
    </connectionStrings>
...

然后将您的代码更改为:

conn.ConnectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
于 2012-10-11T15:07:24.433 回答