c# 读取 mysql,如何从mysql结果中读取某些数据C#

I want to make certain query to mysql from C# so I can get back for example name and lastname.

I don't know how to handle this in c# and I want to minimize sqlinjection.

Here is my code:

con = new MySqlConnection("server=localhost;database=Customers;uid=root;pwd=******");

con.Open();

cmd = new MySqlCommand("SELECT name,lastname FROM customer WHERE ID_customer= ?Parname;", con);

cmd.Parameters.Add("?Parname", MySqlDbType.Float).Value = customer_card;

cmd.ExecuteNonQuery();

con.Close();

I want to be able for example to read results and it will be only one result, in the 2 string variables. How to get trough the data and save it?

Thank you

解决方案

A cheating but quick way of getting several strings out of a query returning one row would be as follows:

con = new MySqlConnection("server=localhost;database=Customers;uid=root;pwd=******");

try {

con.Open();

cmd = new MySqlCommand("SELECT concat(name,'|',lastname) FROM customer WHERE ID_customer= ?Parname;", con);

cmd.Parameters.Add("?Parname", MySqlDbType.Float).Value = customer_card; // Are you sure that the ID is float? That's the first time I see anything like that!

var tokens = ((String)cmd.ExecuteScalar()).Split('|');

var firstName = tokens[0];

var lastName = tokens[1];

Console.Writeln("First={0}, Last={1}", firstName, lastName);

} finally {

con.Close();

}

The idea is to combine both strings into one on the MySql side, and split them back on the C# side. This trick lets you avoid looping through a reader, closing it, and so on. It assumes that the names do not contain '|' characters.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值