题目:
1.查询某一门课程的信息。要查询的课程由用户在程序运行过程中指定,放在主变量中
2.查询选修某一门课程的选课信息,要查询的课程号由用户在程序运行过程中指定,放在主变量中,然后根据用户的要求修改其中某些记录的成绩字段
在VS中配置环境:
首先在vs中选择c#-Windows-控制台
在项目中选择nuget程序包
搜索mysql,安装第一个
环境配置完成
实现1:
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 数据库
{
internal class Program
{
static void Main(string[] args)
{
string connStr = "server=127.0.0.1;port=3306;user=root;password=yourpassword;database=s-t;";
using (MySqlConnection connection = new MySqlConnection(connStr))
{
try
{
Console.WriteLine("Connecting to MySQL...");
connection.Open();
// 用户输入课程名称
Console.Write("Enter the course name to query: ");
string courseName = Console.ReadLine();
// 构造SQL查询语句
string query = "SELECT * FROM course WHERE cname = @CourseName";
using (MySqlCommand command = new MySqlCommand(query, connection))
{
// 使用参数化查询来避免SQL注入
command.Parameters.AddWithValue("@CourseName", courseName);
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int cno = reader.GetInt32("cno");
string cname = reader.GetString("cname");
string cpno = reader.GetString("cpno");
int ccredit = reader.GetInt32("ccredit");
// 输出课程信息
Console.WriteLine("Cno: {0}, cName: {1}, Cpno: {2} , Ccredit: {3}", cno, cname, cpno, ccredit);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Console.WriteLine("Done.");
}
}
}
注意:要将代码中yourpassword改为你自己MySQL的登陆密码
运行结果:
小结1:
- 程序使用了MySql.Data.MySqlClient命名空间提供的类和方法来连接MySQL数据库,并执行查询操作。
- 用户可以输入要查询的课程名称。
- 程序通过使用参数化查询来避免SQL注入攻击。
- 使用MySqlCommand对象的ExecuteReader()方法执行查询,并通过MySqlDataReader对象读取查询结果。
- 程序通过读取MySqlDataReader对象的字段值,将查询结果输出到控制台。
实现2:
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace 数据库2._2
{
internal class Program
{
static string connectionString = "server=localhost;user=root;database=s-t;port=3306;password=yourpassword;"; // 替换为你的连接字符串
static void Main(string[] args)
{
string courseId = GetUserInput("请输入课程号:");
// 查询选课信息
DataTable courseSelections = QueryCourseSelections(courseId);
DisplayCourseSelections(courseSelections);
// 假设用户已经选择了要修改的学号和新的成绩
string studentId = GetUserInput("请输入要修改成绩的学号:");
string newGradeString = GetUserInput("请输入新的成绩:");
decimal newGrade = decimal.Parse(newGradeString);
// 更新成绩
if (UpdateGrade(courseId, studentId, newGrade))
{
Console.WriteLine("成绩更新成功!");
}
else
{
Console.WriteLine("未找到该学生的选课信息或更新失败。");
}
Console.ReadLine(); // 等待用户按键退出
}
static DataTable QueryCourseSelections(string courseId)
{
DataTable dt = new DataTable();
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string sql = "SELECT * FROM sc WHERE cno = @courseId";
using (MySqlCommand command = new MySqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@courseId", courseId);
using (MySqlDataAdapter adapter = new MySqlDataAdapter(command))
{
adapter.Fill(dt);
}
}
}
return dt;
}
static void DisplayCourseSelections(DataTable dt)
{
foreach (DataRow row in dt.Rows)
{
Console.WriteLine($"sno: {row["sno"]}, cno:{row["cno"]},成绩: {row["grade"]}");
}
}
static bool UpdateGrade(string courseId, string studentId, decimal newGrade)
{
bool success = false;
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
string sql = "UPDATE sc SET grade = @newGrade WHERE cno = @courseId AND sno = @studentId";
using (MySqlCommand command = new MySqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@newGrade", newGrade);
command.Parameters.AddWithValue("@courseId", courseId);
command.Parameters.AddWithValue("@studentId", studentId);
int rowsAffected = command.ExecuteNonQuery();
success = rowsAffected > 0;
}
}
return success;
}
static string GetUserInput(string prompt)
{
Console.Write(prompt);
return Console.ReadLine();
}
}
}
注意:yourpassword也要修改为自己的密码
运行结果:
修改前:
修改后:
小结2:
- 程序通过使用MySql.Data.MySqlClient命名空间提供的类和方法连接MySQL数据库,并执行查询和更新操作。
- 使用参数化查询可以有效防止SQL注入攻击,避免了潜在的安全风险。
- 通过使用DataTable和DataAdapter来处理查询结果,使得结果集能够方便地被读取和显示。
- 更新操作通过执行UPDATE语句来实现,根据所影响的行数判断是否更新成功。
实验总结:
- 编写连接代码
- 使用
MySqlConnection
类建立与MySQL数据库的连接。在连接字符串中指定数据库服务器地址、端口、用户名、密码和数据库名称。
- 使用
- 执行查询操作
- 使用
MySqlCommand
类创建SQL查询语句,并通过ExecuteReader
方法执行查询,获取查询结果。 - 使用
MySqlDataReader
类读取查询结果集中的数据,并进行相应的处理。
- 使用
- 执行更新操作
- 同样使用
MySqlCommand
类创建SQL更新语句,并通过ExecuteNonQuery
方法执行更新操作。 - 注意在执行更新操作时,可能需要处理并发更新和数据一致性的问题。
- 同样使用
- 参数化查询
- 为了防止SQL注入攻击,使用参数化查询来构建SQL语句。将用户输入的数据作为参数传递给SQL语句,而不是直接拼接到SQL语句中。
- 异常处理
- 在代码中添加适当的异常处理逻辑,以便在数据库操作出现异常情况时能够捕获并处理异常信息。
- 使用
try-catch
语句块来捕获和处理可能出现的异常。