我試圖插入數據(用戶輸入)到SQL Server數據庫。一切看起來都很好,但實際上並沒有將任何數據插入到數據庫中。隱藏文件(default.aspx.cs
)的代碼如下所示:從asp.net插入數據到SQL Server數據庫
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["mumsDiaryConnectionString"].ConnectionString);
protected void reg_submit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
// storing user input data into variable
var first = reg_first.Text;
var last = reg_last.Text;
var email = reg_email.Text;
var pass = reg_pass.Text.GetHashCode().ToString();
var sub = reg_sub.Text;
var state = reg_state.Text;
var post = reg_post.Text;
var country = "Australia";
try
{
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO user(first, last, email, password, suburb, postcode, state, country) VALUES('"+first+"','"+last+"','"+email+"','"+pass+"','"+sub+"','"+post+"','"+state+"','"+country+"')", connection);
cmd.ExecuteNonQuery();
}
catch(Exception err)
{
Label10.Text = "something gone wrong";
Label10.Text += err.Message;
}
finally
{
connection.Close();
// Response.Redirect("~/Pages/Home_page.aspx");
}
}
}
}
,這是我的web.config文件看起來像:
<?xml version="1.0"?>
<!--For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433-->
<configuration>
<connectionStrings>
<add name="mumsDiaryConnectionString" connectionString="Data Source=MDASHIFURRA73C7\SQLEXPRESS;Initial Catalog=mumsDiary;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.6" />
<httpRuntime targetFramework="4.6" />
</system.web>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
</configuration>
任何人都可以找出這裏有什麼問題嗎?乾杯。
和你得到的錯誤是? –
您是否使用過調試器來遍歷代碼?你得到任何錯誤 – MethodMan
這段代碼是壞的。請不要這樣寫。它很容易被SQL注入。用參數化查詢重寫。 – user1751825