')附近的语法不正确;

时间:2013-10-19 20:24:59

标签: c# mysql asp.net

我的代码出错了。

代码执行直接流向catch块并说:incorrect syntax near ');

我想在数据库中保存一个文件并再次调用它。

public partial class newsrv : System.Web.UI.Page{
    string dir = "C://fileup//";

    protected void Page_Load(object sender, EventArgs e){
        if (!Directory.Exists(dir)){
            Directory.CreateDirectory(dir);
        }
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e){

    }

    protected void Button1_Click(object sender, EventArgs e){
        SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|DB.mdf;Integrated Security=True;User Instance=True");
        string fname = FileUpload1.PostedFile.FileName;
        try{
            SqlCommand cmd = new SqlCommand("INSERT INTO OrderNum (SrviceType, Msg,[File]) VALUES ('" + DropDownList1.SelectedItem.Text + "','" + TextBox1.Text + "' ,'" + FileUpload1.PostedFile.FileName + "') );", con);
            con.Open();

            try {
                int res = cmd.ExecuteNonQuery();
                if (res > 0){
                    System.Windows.Forms.MessageBox.Show("success");
                }
                Label2.Text = TextBox1.Text;
                FileUpload1.SaveAs(dir + fname);
                Label1.Text = " file name uploaded succ ";
                FileUpload1.Visible = true;
            }catch (Exception ex){
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }catch{
            Label1.Text = " file name  not uploaded  ";
            FileUpload1.Visible = false;
            con.Close();
        }finally{
            con.Close();
        }
    }

    protected void TextBox1_TextChanged(object sender, EventArgs e){

    }
}

4 个答案:

答案 0 :(得分:1)

看起来你在SQL语句的末尾有一个额外的); ...

... + TextBox1.Text + "' ,'" + FileUpload1.PostedFile.FileName + "') );", con);

                                                                     ^^ 
                                                                     remove these

答案 1 :(得分:1)

我认为你应该摆脱);在:

  • “'));”,

另外,请考虑使用placeholders来提高安全性。

答案 2 :(得分:0)

您的SQLCommand无效。它应该是:

SqlCommand cmd = new SqlCommand("INSERT INTO OrderNum (SrviceType, Msg,[File]) VALUES ('" + DropDownList1.SelectedItem.Text + "','" + TextBox1.Text + "' ,'" + FileUpload1.PostedFile.FileName + "')", con);

E.G。删除语句末尾的额外);

答案 3 :(得分:0)

不要将);放在查询的末尾。为了便于压缩,请使用以下语法:

SqlCommand cmd=new SqlCommand(String.Format(@"INSERT INTO OrderNum (SrviceType, Msg,[File]) VALUES ('{0},{1},{2}')",DropDownList1.SelectedItem.Text, TextBox1.Text,FileUpload1.PostedFile.FileName),con);

为了更好地理解,更改obj的名称,以便记住你想要做什么。

示例如果您有一个需要用户名的文本框调用文本框txtUserNametxtNickName