[英]Failing SQL insert
我想知道是否有人可以幫助我處理這個 SQL 插入查詢? 我有一種討厭的懷疑,我正在盯着一些非常明顯的東西,但我已經試圖弄清楚一段時間了,但我看不出有什么問題。 目前,當我嘗試執行時,它只是進入 catch 循環。 我正在使用 Visual Studio Community 2015。順便說一下,VS 中是否有任何地方可以嘗試 SQL 語句?
這是代碼
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection myConnection = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = ""C:\Users\Nick\Documents\Investments 4.mdf""; Integrated Security = True; Connect Timeout = 30");
myConnection.Open();
if (myConnection.State == ConnectionState.Open)
{
MessageBox.Show("Connection Open");
}
SqlCommand myCommand3 = new SqlCommand();
myCommand3.CommandType = System.Data.CommandType.Text;
myCommand3.CommandText = "INSERT INTO Dbo.Values (Portfolio Name,Date,Daily Value,Daily Percent) VALUES ('Ascentric',@SQLTime,2000,0.01)";
//myCommand.Parameters.Add("@SQLPortName", System.Data.SqlDbType.NVarChar);
//myCommand.Parameters["@SQLPortName"].Value = "Eric";
myCommand3.Parameters.Add("@SQLTime", System.Data.SqlDbType.DateTime );
myCommand3.Parameters["@SQLTime"].Value = DateTime.Today;
myCommand3.ExecuteNonQuery();
myConnection.Close();
}
catch
{
MessageBox.Show("Nope. Didn't work");
}
}
這是表格:
順便說一句,我確實明白我需要對此進行參數化,但我現在只是想讓基本語句起作用。
任何幫助表示感謝!
如果列名包含空格或保留關鍵字(例如日期),則必須將列名括在括號中:
myCommand3.CommandText = "INSERT INTO Dbo.Values ([Portfolio Name],[Date],[Daily Value],[Daily Percent]) VALUES ('Ascentric',@SQLTime,2000,0.01)";
作為最佳實踐:永遠不要在 SQL 中為對象(列、SPROCS 等)使用空格。 使用 CamelCase 或 underscores_to_separate_words。 因為有一天你會再次忘記括號。
使用 Space 創建列不是要遵循的最佳實踐。 首先刪除空格並將您的列設為單個單詞。 如果您想在選擇時顯示空格,您可以改用別名。
myCommand3.CommandText = "INSERT INTO dbo.Values (PortfolioName,[Date],DailyValue,DailyPercent) VALUES ('Ascentric',@SQLTime,2000,0.01)";
myCommand3.Parameters.Add(new SqlParameter("@SQLTime",DateTime.Today.ToString());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.