SQL Server数据库与我的项目在c#中的同步. [英] SQL Server Database synchronization with my project in c#.

查看:86
本文介绍了SQL Server数据库与我的项目在c#中的同步.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

先生,
我在SQL Server中遇到有关数据库的问题.
我的程序是用C#编写的,可以按我的意愿正常执行,查询中没有错误...
但是数据不会存储回程序要插入或更新的数据库中.
所以请在这方面帮助我.这是示例代码:

Sir,
I am having some problem regarding database in SQL Server.
My program is written in C# executes normally as I want with no errors in my queries...
But data is not stored back to database which the program inserts or updates...
So kindly please help me in this. Here is a sample code :

private void btnLogin_Click(object sender, EventArgs e)
{
  cn.Open();
  cmd = new SqlCommand("insert table_user values(" + id + ",'" + name + "'," + phone_no + "," + status + ")", cn);
  int k = cmd.ExecuteNonQuery();

  if (k > 0)
  {
    Thread form_name = new Thread(new ThreadStart(thread_Proc_form_name));
    form_name.Start();
  }
}

public static void thread_Proc_form_name()
{
  Application.Run(new form_name());
}


这里的cmd是sqlcommand,而cn是sqlconnection,后来我也关闭了连接.
相同类型的代码用作更新:


Here cmd is sqlcommand and cn is sqlconnection and later i closed the connection also.
the same type of code is used as update:

cmd = new SqlCommand("UPDATE table_name SET status = 0 WHERE id = " + key, cn);
int k = cmd.ExecuteNonQuery();

程序可以根据需要运行,但是当我查看数据库表时,不会保存任何更改:(( 请先生,请从这种情况下帮助我. :(
等待您的回复...
谢谢&问候
Saurabh Mahajan.

The program runs as i want but when i look into the database table no changes are saved :((
Please sir, help me from this situation. :(
waiting for your reply...
Thanks & Regards
Saurabh Mahajan.

推荐答案

您的插入语句应像这样
插入表名称(col1,col2,...)VALUES(value1,value2,...)

您还应该使用参数而不是字符串连接并使用块

Your insert statement should be like this
INSERT INTO table_name (col1, col2, ...) VALUES(value1, value2, ...)

You should also be using parameters rather then string concatenation and using blocks

using(SqlConnection conn = new SqlConnection(...))
{
  using(SqlCommand cmd = new SqlCommand(...))
  {
  }
}



连接应尽快打开,并尽快关闭.



Connections should be opened as late as possible and closed as soon as possible.


这篇关于SQL Server数据库与我的项目在c#中的同步.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆