csharp DB CRUD(C#Windows窗体).cs
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp DB CRUD(C#Windows窗体).cs相关的知识,希望对你有一定的参考价值。
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 Database_CRUD_CS__with_SQL_Server_
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnInsert_Click(object sender, EventArgs e)
{
Student student = new Student();
student.Name = txtName.Text;
student.Reg = txtReg.Text;
student.Address = txtAddress.Text;
//CONNECT TO DATABASE
string connectionString = @"Server=(local); " +"Database=UniversityManagementDB; " + "Integrated Security=TRUE;";
SqlConnection connection = new SqlConnection(connectionString);
//WRITE INSERT QUERY
string query = "INSERT INTO tbl_student VALUES('"+student.Name+"','" + student.Reg+"','" + student.Address + "')";
// EXECUTE THE QUERY
SqlCommand command = new SqlCommand(query, connection);
// Two OTHER ways
/* SqlCommand command = new SqlCommand { Connection = connection, CommandText = query}; */
/* SqlCommand command = new SqlCommand{}; */
/* command.CommandText = query;
command.Connection = connection; */
connection.Open();
int rowAffected = command.ExecuteNonQuery();
connection.Close();
if (rowAffected > 0) MessageBox.Show("Inserted "+rowAffected+" Records Successfully");
else MessageBox.Show("Error! Sorry No row inserted");
}
private void btnSelect_Click(object sender, EventArgs e)
{
getAllStudents();
}
public void getAllStudents()
{
// CONNECT TO DATABASE
string connectionSring = "Server=(local); Database=UniversityManagementDB; Integrated Security=TRUE;";
SqlConnection connection = new SqlConnection(connectionSring);
// WRITE THE QUERY
string query = "SELECT * FROM tbl_student";
// EXECUTE THE QUERY
/* read data from database and populate list of objects */
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
List<Student> studentList = new List<Student>();
while (reader.Read())
{
Student student = new Student();
student.ID = int.Parse(reader["ID"].ToString());
student.Name = reader["Name"].ToString();
student.Reg = reader["Reg"].ToString();
student.Address = reader["Address"].ToString();
studentList.Add(student);
}
reader.Close();
connection.Close();
/* populate listview with student list */
listviewStudents.Items.Clear();
foreach (Student student in studentList)
{
ListViewItem item = new ListViewItem();
item.Text = student.ID.ToString();
item.SubItems.Add(student.Name);
item.SubItems.Add(student.Reg);
item.SubItems.Add(student.Address);
item.Tag = student;
listviewStudents.Items.Add(item);
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
Student student = new Student();
student.ID = int.Parse(lblID.Text);
student.Name = txtName.Text;
student.Reg = txtReg.Text;
student.Address = txtAddress.Text;
//CONNECT TO DATABASE
string connectionString = @"Server=(local); " + "Database=UniversityManagementDB; " + "Integrated Security=TRUE;";
SqlConnection connection = new SqlConnection(connectionString);
//WRITE UPDATE QUERY
string query = "UPDATE tbl_student SET Name='" + student.Name + "', Reg='" + student.Reg + "', Address='" + student.Address + "' WHERE ID='"+student.ID+"';";
// EXECUTE THE QUERY
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
int rowAffected = command.ExecuteNonQuery();
connection.Close();
if (rowAffected > 0)
{
getAllStudents();
resetFields();
MessageBox.Show("Row Updated Successfully");
}
else MessageBox.Show("Error! Sorry No row updated");
}
public void resetFields()
{
lblID.Text = string.Empty;
txtName.Text = string.Empty;
txtReg.Text = string.Empty;
txtAddress.Text = string.Empty;
}
private void listviewStudents_DoubleClick(object sender, EventArgs e)
{
if (listviewStudents.SelectedItems.Count > 0)
{
ListViewItem selectedItem = listviewStudents.SelectedItems[0];
Student selectedStudent = (Student) selectedItem.Tag;
txtName.Text = selectedStudent.Name;
txtReg.Text = selectedStudent.Reg;
txtAddress.Text = selectedStudent.Address;
lblID.Text = selectedStudent.ID.ToString();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
int id = int.Parse(lblID.Text);
//CONNECT TO DATABASE
string connectionString = @"Server=(local); " + "Database=UniversityManagementDB; " + "Integrated Security=TRUE;";
SqlConnection connection = new SqlConnection(connectionString);
//WRITE DELETE QUERY
string query = "DELETE FROM tbl_student WHERE ID='"+id+"';";
// EXECUTE THE QUERY
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
int rowAffected = command.ExecuteNonQuery();
connection.Close();
if (rowAffected > 0)
{
getAllStudents();
resetFields();
MessageBox.Show("Deleted " + rowAffected + " Records Successfully");
}
else MessageBox.Show("Error! Sorry No row deleted");
}
}
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Reg { get; set; }
public string Address { get; set; }
}
}
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
namespace VelocityFinCrime.Web.Hubs
{
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
}
public class NotificationService
{
readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
public long GetAllNotification()
{
var count = 0;
using (var connection = new SqlConnection(_connString))
{
connection.Open();
using (var command = new SqlCommand(@"SELECT Id,ActionType,PreviousData,NewData,ActionTable,ModifyBy,ActionBy,UserBranchId,MachineDetails,ActionDateTime FROM dbo.AuditTrails", connection))
{
command.Notification = null;
var dependency = new SqlDependency(command);
dependency.OnChange += dependency_OnChange;
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
count++;
}
}
}
return count;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
NotificationHub.Notify();
}
else
{
Debug.WriteLine(e.Type);
}
}
}
}
以上是关于csharp DB CRUD(C#Windows窗体).cs的主要内容,如果未能解决你的问题,请参考以下文章