使用C#代码(数据集)在SQLSERVER 2005中存储URL

时间:2009-07-23 09:41:06

标签: c# sql-server sql-server-2005 dataset

我试图使用以下代码在按钮点击上存储url。没有错误但是我的列字段中没有所需的url(我使用了ntext数据tpe)。如果有一些请帮助我我的代码中的错误

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public void Storetxt(String txt)
    {


        //connection to the database

        string connection = "Data Source=.\\sqlexpress2005;Initial Catalog=PtsKuratlas;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connection);

       //dataset object to store and manipulating data

        DataSet myDataSet = new DataSet();

        //data adapters to execute SQL

        SqlDataAdapter myDataAdapter = new SqlDataAdapter("SELECT * FROM gti_analytics", conn);
        myDataAdapter.Fill(myDataSet, "gti_analytics");
        myDataAdapter.InsertCommand = new SqlCommand("INSERT INTO gti_analytics [links] VALUES [txt]");




    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        String text = "http://google.com";
        Storetxt(text);
    }
}

4 个答案:

答案 0 :(得分:3)

问题是你实际上并没有对数据库执行命令。您正在定义要使用的InsertCommand,但它没有被执行。

基于该代码,我不认为你需要使用DataAdapter / DataSet,只需使用SqlCommand来执行插入操作,它更轻巧。像这样:

public void Storetxt(String txt)
{
    //connection to the database
    string connection = "Data Source=.\\sqlexpress2005;Initial Catalog=PtsKuratlas;Integrated Security=True";
    SqlConnection conn = null;
    SqlCommand cmd = null;
    try
    {
        conn = new SqlConnection(connection);
        cmd = new SqlCommand("INSERT INTO gti_analytics (Links) VALUES (@Link)", conn);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@Link", txt);
        conn.Open();
        cmd.ExecuteNonQuery();
    }
    catch{//handle exceptions}
    finally
    {
        if (cmd != null) cmd.Dispose();
        if (conn != null) 
        {
            if (conn.State == ConnectionState.Open) conn.Close();
            conn.Dispose();
        }
    }
}

我还建议不要在db中使用ntext。如果你真的需要unicode支持,可以使用nvarchar,它可以在pre-sql 2005之前达到4000个字符,或者nvarchar(max),它可以存储与SQL 2005之后的ntext一样多的内容。如果您不需要unicode支持,请改用varchar(8000 chars pre-sql 2005,从SQL 2005开始的VARCHAR(MAX)允许与文本相同)

答案 1 :(得分:1)

你不应该在Storetxt方法的末尾调用myDataAdapter.Update()吗? 哦,我认为使用ntext是有点矫枉过正的。

答案 2 :(得分:0)

您的txt方法参数实际上并未在您的方法中的任何位置使用,这是其未存储在数据库中的一个原因。

答案 3 :(得分:0)

AdaTheDev表示,此操作不需要 SqlDataAdapter DataSet 。请按照示例代码进行操作,但需要进行相当多的清理。

此外,URL中的字符数/字节数有协议限制, nvarchar 应具有足够的最大容量,因此您既不需要 nvarchar(max) nor(pre-SQL Server 2005) ntext