当前位置:网站首页>C summary of knowledge points 3
C summary of knowledge points 3
2022-07-01 11:46:00 【dengfengling999】
1. Database connection steps :Connection object
//1. Construct connection string
string strconn = "Data Source=.;Initial Catalog=studentInf;Integrated Security=True";
//2. Construct connection objects
SqlConnection s = new SqlConnection(strconn);
//try To prevent abnormalities
try
{
//3. Open the connection
s.Open();
MessageBox.Show(" Database open ");
}
// If there is an exception, it will be displayed
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
// Database shutdown
finally
{
s.Close();
MessageBox.Show(" Database shutdown ");
}
2. Database operation :Command object - Login box connection database
1. Database connection
string strconn = "Data Source=.;Initial Catalog=studentInf;Integrated Security=True";
SqlConnection conn = =new SqlConnection(strconn);
// Receive the input user name in the text box 、 password :
string name = txtUserName.Text;
string pwd = txtUserPwd.Text;
try
{
conn.Open();
2. Definition SQL sentence
string sqlstr=string.Format("select * from tb_User where UserName='{0}' and UserPasswd='{1}'",name,pwd);
3. establish Command The object of // Encapsulates all operations on external data sources ( Include add delete change check )
Method 1
SqlCommand comm = newSqlCommand();
comm.Connection = conn;//Connection Property settings get Command Object used Connection object
comm.CommandText = sqlstr;//CommandText Property is used to set or get the SQL sentence
Method 2
SqlCommand comm2 = newSqlCommand(sqlstr, conn);
// Execute the query ,
if (comm.ExecuteScalar() == null)// ExecuteScalar() Method to execute the query , And return the query results. The first row and the first column in the query result set (object type ), Return if not found null
{
MessageBox.Show(" User name and password do not match , Login failed ");
}
else
{
// Login to another with the correct password framain Main form page
frmMain frmmain = newfrmMain();
frmmain.Show();// Show main window
}
}
catch (Exception ex)// Abnormal display appears
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();// Close database connection
}
}
3 Then add information to the database in the form
string conn = "Data Source=.;Initial Catalog=studentInf;Integrated Security=True";
SqlConnection a = newSqlConnection(conn);
if (txtCollegeNo.Text == "" || txtCollegeName.Text == "")// Determine whether the form input box is empty
{
MessageBox.Show(" Department number or department name cannot be empty ");
}
else
{
try
{
- Open();// Database open
// add to SQL sentence
string sqlstr = string.Format("insert into tb_College values('{0}','{1}')", txtCollegeNo.Text, txtCollegeName.Text);
//Command object
SqlCommand comm = newSqlCommand();
comm.Connection = a;
comm.CommandText = sqlstr;
int result = comm.ExecuteNonQuery();// perform ExecuteNonQuary Method returns a int value , The return value is the number of lines affected by the command
if (result != 0)
{
MessageBox.Show(" Insert the success ");
}
else
{
MessageBox.Show(" insert ? Enter into ¨? loss º¡ì Defeat 㨹");
}
}
catch (Exception ex)
{
// Display exception
MessageBox.Show(ex.Message);
}
finally
{
a.Close();// Database shutdown
}
4. Enter the Department query information , And display in the form box
string conn = "Data Source=.;Initial Catalog=studentInf;Integrated Security=True";
SqlConnection a = newSqlConnection(conn);
try
{
- Open();
// Query statement
string sqlstr = string.Format("select * from tb_College where DepartmentID='{0}'", txtCollegeNo.Text);
SqlCommand comm = newSqlCommand();
comm.Connection = a;
comm.CommandText = sqlstr;
// establish DataReader object ,DataReader Objects cannot be instantiated directly with constructors , Must pass Command Object's ExecuteReader() Method to generate .
SqlDataReader read = comm.ExecuteReader();
if (read.Read())// call Read() Method , Find out
{
// Put the second column of data queried in txtCollegeName The box displays
txtCollegeName.Text = read[1].ToString();
}
else
{
// If the query cannot find the output
MessageBox.Show(" The query result does not exist ");
txtCollegeName.Text = "";// Clear query results
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
a.Close();
}
4. Delete the queried data
DBhelp Is a help class , Can be called directly
try
{
DBhelp.conn.Open();
//SQL Delete statements
string sqlstr = string.Format("delete from tb_College where DepartmentID='{0}'and DepartmentName='{1}' ", txtCollegeNo.Text, txtCollegeName.Text);
DBhelp.comm.CommandText = sqlstr;
DBhelp.comm.Connection = DBhelp.conn;
if ((int)DBhelp.comm.ExecuteNonQuery() > 0)// call Command object ExecuteNonQuery() Method returns the number of affected rows
{
MessageBox.Show(" Delete successful ");
}
else
{
MessageBox.Show(" Delete failed ");
}
}
catch (Exception ex)
{
// Display exception
MessageBox.Show(ex.Message);
}
finally
{
// Close database connection
DBhelp.conn.Close();
}
5. Use the form to update the database
…
边栏推荐
猜你喜欢
Harbor webhook from principle to construction
Tianrunyun, invested by Tian Suning, was listed: its market value was 2.2 billion Hong Kong, and its first year profit decreased by 75%
2022/6/30学习总结
Comment Cao définit la décimale de dimension
为什么一定要从DevOps走向BizDevOps?
二叉堆(一) - 原理与C实现
Adjacency matrix undirected graph (I) - basic concepts and C language
TEMPEST HDMI泄漏接收 3
Redis' attack tactics
基于IMDB评论数据集的情感分析
随机推荐
How does Nike dominate the list all the year round? Here comes the answer to the latest financial report
内核同步机制
Istio、eBPF 和 RSocket Broker:深入研究服务网格
索引失效的几种情况
Numpy的矩阵
想问问,证券开户有优惠吗手机开户是安全么?
sshd_ Discussion on permitrotlogin in config
Deep understanding of grpc part1
2022/6/28学习总结
IPlImage的width和widthStep
用实际例子详细探究OpenCV的轮廓检测函数findContours(),彻底搞清每个参数、每种模式的真正作用与含义
Are the consequences of securities account cancellation safe
No statements may be issued when any streaming result sets are open and in use on a given connection
Continuous delivery -pipeline getting started
耐克如何常年霸榜第一名?最新财报答案来了
Tempest HDMI leak receive 3
Kernel synchronization mechanism
[buuctf.reverse] 144_ [xman2018 qualifying]easyvm
Neo4j Chinese developer monthly - issue 202206
Skip the test cases to be executed in the unittest framework