Bur*_*Dor 4 c# mysql web-services
我正在尝试在.NET中构建一个Web服务,它将从mySQL数据库中检索数据.此Web服务稍后将与将显示此数据的Windows窗体组合.
到现在为止,我已经准备好了数据库,数据库和Web服务之间的连接已经完成,表单也已准备就绪.
但是,我无法从表本身检索特定的信息.任何人都可以帮我弄清楚我的下一步应该是什么?我在这个问题上搜索过很多但我仍然无法找到关于这个问题的好教程...如果您有任何想法,那么请您也发布链接吗?提前致谢!
附加信息:假设一个名为"testdata"的样本表,其中有三列("id","name","age").如何提取名称和年龄并在表单上显示?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace WebService2
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
private void connectoToMySql()
{
string connString = "SERVER=localhost" + ";" +
"DATABASE=testdatabase;" +
"UID=root;" +
"PASSWORD=password;";
MySqlConnection cnMySQL = new MySqlConnection(connString);
MySqlCommand cmdMySQL = cnMySQL.CreateCommand();
MySqlDataReader reader;
cmdMySQL.CommandText = "select * from testdata";
cnMySQL.Open();
reader = cmdMySQL.ExecuteReader();
//-----------------------------------------------------------
// This is the part where I should be able to retrieve the data from the database
//-----------------------------------------------------------
cnMySQL.Close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
创建一个公共的方法,用WebMethodAttribute标记,并返回一个DataTable(如果您的使用者是.net客户端).让消费者调用该方法并使用DataTable执行任何操作.
[System.Web.Services.WebMethod]
public DataTable connectoToMySql()
{
string connString = "SERVER=localhost" + ";" +
"DATABASE=testdatabase;" +
"UID=root;" +
"PASSWORD=password;";
MySqlConnection cnMySQL = new MySqlConnection(connString);
MySqlCommand cmdMySQL = cnMySQL.CreateCommand();
MySqlDataReader reader;
cmdMySQL.CommandText = "select * from testdata";
cnMySQL.Open();
reader = cmdMySQL.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
cnMySQL.Close();
return dt;
}
Run Code Online (Sandbox Code Playgroud)