0

net 添加数据库。我正在尝试在两个文本框和下拉列表中的一个选定值上添加文本以添加我的表格。这是我的代码

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

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string connectionString = @" Data Source=.\SQLEXPRESS;AttachDbFilename=C:\USERS\CEM\DOCUMENTS\VISUAL STUDIO 2010\WEBSITES\EKLEMEDENE\APP_DATA\DATABASE.MDF;Integrated Security=True;User Instance=True";
        string queryString = "INSERT INTO ekle(flight, name, food) VALUES   ('" + TextBox1.Text + " ' , '" + TextBox2.Text + " ' ,  '" + DropDownList1.SelectedValue + " '  )";
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(queryString, con);
        con.Open();
        command.ExecuteNonQuery();

        con.Close();
    }
}

执行后我会出错

数据库“C:\Users\Cem\Documents\Visual Studio 2010\WebSites\eklemedene\App_Data\Database.mdf”已经存在。选择不同的数据库名称。尝试为文件 C:\USERS\CEM\DOCUMENTS\VISUAL STUDIO 2010\WEBSITES\EKLEMEDENE\APP_DATA\DATABASE.MDF 附加自动命名数据库失败。存在同名数据库,或无法打开指定文件,或位于 UNC 共享上。

4

1 回答 1

1
  1. 你对 SQL 注入很开放。避免直接从控件传递参数。而是使用Parameters.
  2. 用于using-statement任何实现IDisposable,如连接或命令:
  3. 您的 ConnectionString 有问题,您可以尝试使用SqlConnectionStringBuilder类:

//Build the connection 
SqlConnectionStringBuilder bldr = new SqlConnectionStringBuilder();

//Put your server or server\instance name here.  Likely YourComputerName\SQLExpress
bldr.DataSource = ".\\SQLEXPRESS";

//Attach DB Filename
bldr.AttachDBFilename = @"C:\USERS\CEM\DOCUMENTS\VISUAL STUDIO 2010\WEBSITES\EKLEMEDENE\APP_DATA\DATABASE.MDF";

//User Instance
bldr.UserInstance = true;

//Whether or not a password is required.
bldr.IntegratedSecurity = true;

using(var connection = new SqlConnection(bldr.ConnectionString))
{
    var sql = "INSERT INTO ekle(flight, name, food) VALUES (@flight, @name , @food)";
    using(var command = new SqlCommand(sql, connection))
    {
        command.Parameters.AddWithValue("@flight", TextBox1.Text);
        command.Parameters.AddWithValue("@name", TextBox2.Text);
        command.Parameters.AddWithValue("@food", DropDownList1.SelectedValue); 
        connection.Open();
        command.ExecuteNonQuery();
    }
} // closes the connection implicitely
于 2012-05-14T15:24:25.897 回答