【发布时间】:2016-05-01 11:32:54
【问题描述】:
使用 C# windows 窗体应用程序开发员工/学生管理系统。
两名开发人员正在开发这个项目,并使用两个版本的 Visual Studio 和 SQL Server。 (一台 PC 使用 VS 2013 Pro 和 MS SQL express 14,另一台 PC 使用 VS 2015 企业版和 SQL 14 企业版)。两台 PC 都通过团队基础服务器工作。
C# 应用程序正在连接 SQL 数据库,并通过登录界面验证数据检索。用户名和密码存储在一个表中,登录过程正常。所以可以确定DB连接没有错误。
问题是当我们尝试向SQL表中插入数据时,C#在try/catch exceptions中显示没有错误,但数据并没有存储在数据库中。也用过command.ExecuteNonQuery()。
不确定连接字符串有问题。
这是connectionManager 类。
class ConnectionManager
{
public static SqlConnection connection()
{
string connectionString =
@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\tdsdb.mdf;Integrated Security=True";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
return con;
}
}
这是处理 SQL 插入操作的类。
class Student
{
public void addStudent(string studid, string fullname, string nameinit, string gend, string dob, int age, string nic, string nicdate, string hotp, string mobtp, string odlno, string odldt, string odlcls, string reqdlcls, int trtds, int active)
{
string sql= "INSERT INTO tblStudent VALUES ('"+studid+"','"+fullname+"','"+nameinit+"','"+gend+"','"+dob+"','"+age+"','"+nic+"','"+nicdate+"','"+hotp+"','"+mobtp+"','"+odlno+"','"+odldt+"','"+odlcls+"','"+reqdlcls+"','"+trtds+"','"+active+"')";
SqlCommand com = new SqlCommand(sql, ConnectionManager.connection());
com.ExecuteNonQuery();
}
}
这是处理提交按钮点击操作的类
private void button6_Click(object sender, EventArgs e)
{
string radtext = "";
bool isChecked = radioButton1.Checked;
if(isChecked)
radtext = radioButton1.Text;
else
radtext = radioButton2.Text;
string hometp = "+94"+textBox8.Text;
string mobiletp = "+94"+textBox9.Text;
int activeint = 1;
string trtdschk = comboBox3.Text;
int trtds = 0;
if (trtdschk == "Yes")
trtds = 1;
else
trtds = 0;
try
{
std.addStudent(textBox2.Text, textBox38.Text, textBox4.Text, radtext, dateTimePicker2.Text, int.Parse(textBox6.Text), textBox7.Text, dateTimePicker3.Text, hometp, mobiletp, textBox12.Text, dateTimePicker4.Text, comboBox1.Text, comboBox2.Text, trtds, activeint);
MessageBox.Show("Personal details has been successfully added to the database!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
【问题讨论】:
-
不知道多个数据库连接如何相互影响,您应该尝试只维护单个数据库连接。例如,通过使用单例进行数据库连接。
-
不要使用 mdf 文件名作为连接字符串。而是连接到服务器名称并包含“使用数据库名称”语句。数据库可能已经附加到数据库,不需要每次使用数据库时附加。
-
只是指出您的代码似乎容易受到 SQL 注入攻击。
-
您的数据库已经附加到项目中,将字符串更改为这样,在您的配置中,
<connectionStrings><add name="db" connectionString="data source=LOCALMACHINENAME\SQLEXPRESS; initial catalog=name of database; integegrated security=true" providerName="System.Data.SqlClient" /></connectionStrings>
标签: c# sql-server database