当前位置:网站首页>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
…
边栏推荐
- 用于分类任务的数据集划分脚本
- Y48. Chapter III kubernetes from introduction to mastery -- pod status and probe (21)
- Dameng data rushes to the scientific innovation board: it plans to raise 2.4 billion yuan. Feng Yucai was once a professor of Huake
- Xiaomi mobile phone unlocking BL tutorial
- activity工作流引擎
- Value/string in redis
- ACLY与代谢性疾病
- Istio、eBPF 和 RSocket Broker:深入研究服务网格
- Deep understanding of grpc part1
- TMUX usage
猜你喜欢
随机推荐
Unittest框架中测试用例编写规范以及如何运行测试用例
Vscode shortcut key (the most complete) [easy to understand]
内核同步机制
Shangtang entered the lifting period: the core management voluntarily banned and strengthened the company's long-term value confidence
用于分类任务的数据集划分脚本
ES6 Promise用法小结
耐克如何常年霸榜第一名?最新財報答案來了
索引失效的几种情况
I'm in Zhongshan. Where is a better place to open an account? Is it actually safe to open an account online?
Redis启动与库进入
Can I open an account today and buy stocks today? Is it safe to open an account online?
Dameng data rushes to the scientific innovation board: it plans to raise 2.4 billion yuan. Feng Yucai was once a professor of Huake
Talk about the pessimistic strategy that triggers full GC?
IPlImage的width和widthStep
深入理解 grpc part1
Can solo be accessed through IPv6?
Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
CAD如何设置标注小数位
Brief explanation of the working principle, usage scenarios and importance of fingerprint browser
241. 为运算表达式设计优先级 : DFS 运用题








