2013-05-28 129 views
0

我的代碼有什麼問題?當我設置SQL Server和C#之間的連接時,它給了我這個錯誤「ExecuteNonQuery:連接屬性尚未初始化。」收到錯誤「ExecuteNonQuery:連接屬性尚未初始化。」我跑我的程序

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Data.SqlClient; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace Essencia 
{ 
    public partial class NewReservation : Form 
    { 
     public NewReservation() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     SqlConnection con = new SqlConnection(); 
     con.ConnectionString= "Database= hotel; server= Roger\SQLEXPRESS"; 
     con.Open(); 
     SqlCommand cmd = new SqlCommand("insert into CheckIn values(@TransactionId,@GuestName,@RoomType,@RoomNo,@ReservationDate,@CheckInDate,@CheckOutDate,@NoOfDays,@NoOfAdults,@NoOfChildren)"); 
     cmd.Parameters.AddWithValue("@TransactionId",textBox1.Text); 
     cmd.Parameters.AddWithValue("@GuestName", textBox2.Text); 
     cmd.Parameters.AddWithValue("@RoomType", textBox3.Text); 
     cmd.Parameters.AddWithValue("@RoomNo", textBox4.Text); 
     cmd.Parameters.AddWithValue("@ReservationDate", textBox5.Text); 
     cmd.Parameters.AddWithValue("@CheckInDate", textBox6.Text); 
     cmd.Parameters.AddWithValue("@CheckOutDate", textBox7.Text); 
     cmd.P`enter code here`arameters.AddWithValue("@NoOfDays", textBox8.Text); 
     cmd.Parameters.AddWithValue("@NoOfAdults", textBox9.Text); 
     cmd.Parameters.AddWithValue("@NoOfChildren", textBox10.Text); 

     cmd.ExecuteNonQuery(); 
     con.Close(); 
     MessageBox.Show("DATA ADDED SUCCESSFULLY!!"); 
    } 
} 

}

+2

什麼是堆棧跟蹤? – SLaks

回答

0

哪裏INSERT INTO SQL的VALUES一部分?

側面說明:您還應該使用using語句來以確保連接,即使在異常關閉的情況下:

string sql = @"INSERT INTO checkin 
         (transactionid, 
         guestname, 
         roomtype, 
         roomno, 
         reservationdate, 
         checkindate, 
         checkoutdate, 
         noofdays, 
         noofadults, 
         noofchildren) 
       VALUES(@TransactionId, 
         @GuestName, 
         @RoomType, 
         @RoomNo, 
         @ReservationDate, 
         @CheckInDate, 
         @CheckOutDate, 
         @NoOfDays, 
         @NoOfAdults, 
         @NoOfChildren)"; 

using(var con = new SqlConnection(@"Database= hotel; server= Roger\SQLEXPRESS")) 
using(var cmd = new SqlCommand(sql , con)) 
{ 
    cmd.Parameters.AddWithValue("@TransactionId",textBox1.Text); 
    // other parameters as well 
    con.Open(); 
    cmd.ExecuteNonQuery(); 
} 
1

在你調用SqlCommand構造函數中添加連接對象在你的SQL之後:

using (SqlCommand cmd = new SqlCommand(
     "insert into CheckIn values(@TransactionId,@GuestName,@RoomType,@RoomNo,@ReservationDate,@CheckInDate,@CheckOutDate,@NoOfDays,@NoOfAdults,@NoOfChildren)", 
     con)) 
    { 
     //... 
    } 
+0

奇怪的是,你之前發佈的問題有'con'被傳入,但是你的最新版本沒有。你不能傳入它,因爲這是錯誤所表示的。 – Jacob

相關問題