-1

大家好,我需要一些有关此数据管道的帮助。它是我的导师写的,我们在一个 Web 开发项目中使用它。我正在尝试将它用于 Windows 窗体应用程序以连接到数据库,但出现以下错误:

尝试为文件 C:\Users.... 附加自动命名的数据库失败。存在同名数据库,或无法打开指定文件,或位于 UNC 共享上。

如果我在 asp.net 网站上使用它而不是在我尝试研究但没有运气的 Windows 窗体上使用它,数据管道确实有效。我只是用两个文本框和一个保存按钮来测试它
谢谢

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data;

///This class uses the ado.net sql classes to provide a connection to an sql server database.
///it is free for use by anybody so long as you give credit to the original author i.e me
///Matthew Dean mjdean@dmu.ac.uk De Montfort University 2011

//you will need to modify the name of the namespace to suit your own program.
namespace MyClassLibrary
{
    public class clsDataConduit
    {
        //connection object used to connect to the database
        SqlConnection connectionToDB = new SqlConnection();
        //data adapter used to transfer data to and from the database
        SqlDataAdapter dataChannel = new SqlDataAdapter();
        //ado.net class for building the sql commands
        SqlCommandBuilder commandBuilder = new SqlCommandBuilder();
        //stores a list of all of the sql parameters
        List<SqlParameter> SQLParams = new List<SqlParameter>();
        //data table used to store the results of the stored procedure
        DataTable queryResults = new DataTable();
        //data row used to store the data for a new record
        DataRow newRecord;
        //string variable used to store the connection string
        private string connectionString;

        public clsDataConduit()
        {
            //this is the constructor for the class
            //you will need to modify this to suit your own database name and folder structure
            //
            //variable to store the patth to the database
            string DbPath;
            //variable to store the partial path and file name of your database 
            //modify this line to suit your own needs
            string DatabaseName = "\\MyDatabase\\NamesData.mdf";
            //set the DbPath concatenating the name of your database
            DbPath = GetParentPath() + DatabaseName;
            //build up the connection string for the sql server database
            connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + DbPath + ";Integrated Security=True;User Instance=True";
        }

        private string GetParentPath()
        ///this function returns the path to the parent folder of the solution
        {
            //get the folder for the project
            string DbPath = System.AppDomain.CurrentDomain.BaseDirectory;
            //variable to store the position of the \\ characters
            int Posn;
            //loop through the path twice
            for (int Counter = 0; Counter != 2; Counter++)
            {
                //find the right most instance of \\
                Posn = DbPath.LastIndexOf("\\");
                //split the path at that point
                DbPath = DbPath.Substring(0, Posn);
                //do it one more time
            }
            //return the new path
            return DbPath;
        }

        public void AddParameter(string ParamName, string ParamValue)
        ///public method allowing the addition of an sql parameter to the list of parameters
        ///it accepts two parameters the name of the parameter and its value
        {
            //create a new instance of the sql parameter object
            SqlParameter AParam = new SqlParameter(ParamName, ParamValue);
            //add the parameter to the list
            SQLParams.Add(AParam);
        }

        public void Execute(string SProcName)
        {
            ///public method used to execute the named stored procedure
            ///accepts one parameter which is the name of the stored procedure to use
            //open the stored procedure
            //initialise the connection to the database
            connectionToDB = new SqlConnection(connectionString);
            //open the database
            connectionToDB.Open();
            //initialise the command builder for this connection
            SqlCommand dataCommand = new SqlCommand(SProcName, connectionToDB);
            //add the parameters to the command builder
            //loop through each parameter
            for (int Counter = 0; Counter < SQLParams.Count; Counter += 1)
            {
                //add it to the command builder
                dataCommand.Parameters.Add(SQLParams[Counter]);
            }
            //set the command type as stored procedure
            dataCommand.CommandType = CommandType.StoredProcedure;
            //initialise the data adapter
            dataChannel = new SqlDataAdapter(SProcName, connectionToDB);
            //set the select command property for the data adapter
            dataChannel.SelectCommand = dataCommand;
            //use the copmmand builder to generate the sql insert delete etc
            commandBuilder = new SqlCommandBuilder(dataChannel);
            //fill the data adapter
            dataChannel.Fill(queryResults);
            //get the structure of a single record
            newRecord = queryResults.NewRow();
            //close the connection
            connectionToDB.Close();
        }

        public void WriteToDatabase()
        //void method that updates changes to the data adapter thus changing the database
        {
            //update any changes
            dataChannel.Update(queryResults);
        }

        public DataRow NewRecord
        ///this method provides access to the new record as a single data row
        {
            get
            {
                //return the blank data row
                return newRecord;
            }
        }

        public void RemoveRecord(int Index)
        //void method that removes a record at a specified index in the query results
        {
            //remove the record
            queryResults.Rows[Index].Delete();
        }

        public void AddToDataTable()
        //void method that adds the new record to the table data
        {
            //add the new record to the table 
            queryResults.Rows.Add(newRecord);
            //re initialise the new record
            newRecord = queryResults.NewRow();
        }

        public int Count
        //property that returns the count of records in the query results
        {
            get
            {
                //return the count of the query results
                return queryResults.Rows.Count;
            }
        }

        public DataTable QueryResults
        //public property that provides access to the query results
        {
            get
            {
                //return the query results
                return queryResults;
            }
            set
            {
                //set the query results
                queryResults = value;
            }
        }
    }
}

这是我的名字类的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyClassLibrary
{
   public class clsName
    {
       private string firstName;
       private string lastName;

       public string FirstName
       {
           get
           {
               return firstName;
           }

           set
           {
               firstName = value;
           }
       }

       public string LastName
       {
           get
           {
               return lastName;
           }

           set
           {
               lastName = value;
           }
       }

       public void Save()
       {
           clsDataConduit Names = new clsDataConduit();
           Names.Execute("sproc_tblNames_GetAll");
           Names.NewRecord["FirstName"] = firstName;
           Names.NewRecord["LastName"] = lastName;
           Names.AddToDataTable();
           Names.WriteToDatabase();
       }




    }
}
4

1 回答 1

0

谢谢你们,但我终于设法使它工作。我不确定这是否是正确的方法,但你所做的是我已经注释掉了公共 clsDataConduit() {} 方法,在此方法之前我修改了连接字符串,添加了我的数据库的完整路径,如下所示: 私有字符串 connectionString = (@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users...\NamesData.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");

于 2012-12-01T14:02:50.360 回答