我有一个连接数据库的类并执行查询
public class dbConnect
{
public MySqlConnection Connection { get; set; }
public MySqlCommand cmd;
...
public void Connetti()
{
try
{
if (Connection.State == ConnectionState.Closed)
{
Connection.Open();
}
}
catch (Exception ex)
{
MessageBox.Show("Errore " + ex.Message);
}
}
如何返回MySqlCommand cmd?
public void SetQuery(string sSQL)
{
MySqlCommand cmd = new MySqlCommand(sSQL, Connection);
//return cmd.ExecuteReader();
}
}
让MySqlCommand实例返回是有用的,用于datatable.Load => dt.Load(cmd.ExecuteReader());
public MainWindow()
{
InitializeComponent();
conn.Connetti();
//MySqlCommand cmd = new MySqlCommand("SELECT * FROM tb_navi Order By NOMENAVE", conn.Connection); conn.SetQuery("SELECT * FROM tb_navi Order By NOMENAVE");
System.Data.DataTable dt = new System.Data.DataTable();
//dt.Load(cmd.ExecuteReader());
dt.Load(conn.cmd); //now cmd is null
dtGrid.DataContext = dt;
}
答案 0 :(得分:2)
从您的方法中返回已填充的DataTable
:
public DataTable SetQuery(string sSQL)
{
DataTable dt = new DataTable();
using (MySqlCommand cmd = new MySqlCommand(sSQL, Connection))
{
_cmd.ExecuteNonQuery();
using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
return dt;
}
答案 1 :(得分:1)
试试这个
public DataTable GetTableData(string StrSQL)
{
DataTable dataTable = new DataTable();
MySqlCommand mySqlCommand = null;
MySqlDataReader mySqlDataReader = null;
try
{
mySqlCommand = new MySqlCommand(StrSQL, Connection);
mySqlDataReader = mySqlCommand.ExecuteReader();
dataTable.TableName = "mydata";
dataTable.Load(mySqlDataReader);
}
finally
{
if (mySqlDataReader != null)
{
if (!mySqlDataReader.IsClosed)
{
mySqlDataReader.Close();
}
}
}
return dataTable;
}