c与数据库连接的详细步骤

c与数据库连接的详细步骤,第1张

C#连接数据库有以下几个步骤:

1:使用配置的数据库连接串,创建数据库连接 Connection 对象

2:构建 *** 作的sql语句

3:定义command对象

4:打开数据连接

5:执行命令

举一个例子,删除 *** 作

public class StudentService

{

//从配置文件中读取数据库连接字符串

private readonly static string connString = ConfigurationManager.ConnectionStrings["accpConnectionString"].ToString()

private readonly static string dboOwner = ConfigurationManager.ConnectionStrings["DataBaseOwner"].ToString()

AdoNetModels.Student model = new Student()

#region 删除数据1

public int DeleteStudent(int stuID)

{

int result = 0

// 数据库连接 Connection 对象

SqlConnection connection = new SqlConnection(connString)

// 构建删除的sql语句

string sql = string.Format("Delete From Student Where stuID={0}", stuID)

// 定义command对象

SqlCommand command = new SqlCommand(sql, connection)

try

{

connection.Open()

result = command.ExecuteNonQuery() // 执行命令

}

catch (Exception ex)

{

Console.WriteLine(ex.Message)

}

finally

{

connection.Close()

}

return result

}

#endregion

eclipse如何使用JDBC连接mysql数据库:

1.在新建的Project中右键新建Floder

2.创建名为lib的包

3.创建完毕之后的工程目录

4.接下来解压你下载的mysql的jar包,拷贝其中的.jar文件

5.在工程lib包下邮件 选择paste即粘贴,把mysql的jar包拷贝进来

6.拷贝完毕如图:

7.在mysql的jar包上右键选择 build path - add to build path

8.添加完毕之后,工程才与Mysql的jar包关联起来,现在可以使用相关类和方法了

9.在工程中新建JdbcTest1.java类

10.输入如下代码:

11.代码解释:

Driver是个实现类,它由具体的数据库厂商来实现。它的connect方法可以获取数据库连接。参数如上图。运行之后,输出如下,证明数据库连接成功!

12.说明:这个是使用Driver连接数据库的,而通常开发中使用的是DriverManager或数据库连接池,这个仅作为理解数据库连接事例使用。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/sjk/9994735.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-04
下一篇2023-05-04

发表评论

登录后才能评论

评论列表(0条)

    保存