将节目上的输入保存到数据库中
问题描述:
我正在为我在大学的项目讲座开发酒店管理系统。我请你帮我解决下面粘贴的代码。我不明白为什么它不会传输和保存我在Visual Studio Express中输入的输入。这是代码:将节目上的输入保存到数据库中
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
class Database
{
SqlConnection con;
public Database()
{
con = new SqlConnection("server=.,database=Guest; Integrated Security = True");
}
public bool AddGuest(string ID, string Phone, string Adress, string FName, string LName, string Email, string RoomNo)
{
bool durum = false;
SqlCommand cmd = new SqlCommand(@"declare @guest_id nvarchar(50),@guest_phone nvarchar(50),@guest_adress ntext,@guest_fname ntext,@guest_lname ntext,@guest_email ntext,@room_no int = @room_no;
select @guest_id = Guest.guest_id from Guest where Guest.room_no = '103';
select @guest_phone = Guest.guest_phone from Guest where Guest.room_no = '103';
select @guest_adress = Guest.guest_adress from Guest where Guest.room_no = '103';
select @guest_fname = Guest.guest_fname from Guest where Guest.room_no = '103';
select @guest_lname = Guest.guest_lname from Guest where Guest.room_no = '103';
select @guest_email = Guest.guest_email from Guest where Guest.room_no = '103';
insert into Guest(guest_id,guest_phone,guest_adress,guest_fname,guest_lname,guest_email,room_no)values(@guest_id,@guest_adress,@guest_fname,@guest_lname,@guest_email,@room_no)
)", con);
cmd.Parameters.AddWithValue("@id", ID);
cmd.Parameters.AddWithValue("@phone", Phone);
cmd.Parameters.AddWithValue("@adress", Adress);
cmd.Parameters.AddWithValue("@fname", FName);
cmd.Parameters.AddWithValue("@lname", LName);
cmd.Parameters.AddWithValue("@email", Email);
cmd.Parameters.AddWithValue("@room_no", RoomNo);
con.Open();
try
{
cmd.ExecuteNonQuery();
durum = true;
}
catch (Exception)
{
}
con.Close();
return durum;
}
private void ekle_Click(object sender, EventArgs e)
{
}
}
}
例如,当你在图片中看到的,我进入来宾ID,姓氏,名字,然后我希望他们能够被保存在数据库。我将数据库与视觉连接起来,并根据它创建了代码。但仍然不起作用。
答
将该SQL语句删除并将其放入SQL Server Management Studio并查看它是否运行。你会看到它会抛出一些错误,主要是由于你的变量。
有几件事情我在简要回顾发现:
- 不要使用NTEXT改变那些声明为varchar(50)。
- @room_no int = @room_no将会失败。 (你的意思是@roomno =“” + RoomNo +“')
- 你的参数addwithvalue不要在您的SQL匹配参数(是你意识到这一点?)
您的连接字符串应该是服务器=。\ SQLExpress或。\ SQLStandard。我将使用SQL Server随附的SQL Server Management Studio(SSMS)来帮助调试问题。您可以查询数据库以验证是否添加了数据。连接字符串中服务器的名称应该与SSMS的登录窗口相同。您可能正在写入错误的数据库,请检查SSMS资源管理器中的所有数据库。 – jdweng
只有一个数据库,而且我也在使用SQL Server Management Studio 2014.这是我的数据库登录屏幕的屏幕截图:http://i.hizliresim.com/MoayGg.png 而这个是里面的截图: http://i.hizliresim.com/DByRbv.png –
您的连接字符串应该是server =,\ cembilal或server = CEM-BILAL \ cembilal。 'cembilal'是数据库的实例。你的数据库名也是错的,应该是hocu(不是Guest)。我通常在我的SQL语句中将'使用hocu'放在查询开始处选择正确的数据库。或者将数据库名称添加到连接字符串。您没有指定让我相信您正在写入另一个SQL Server实例的hocu。在你的情况下SQL Server的实例是cembilal。我怀疑你的PC上安装了两个SQL Server实例。 – jdweng