本人初学c#,数据库用的是Mysql 现在的问题是这样的。一个按钮按下是连接数据库另外一个按钮按下后查表。但是明明我那张表有3行数据,可是不管咋查都是1行。求高手解答!
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace MyPro_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
}
MySqlConnection conn;
MySqlCommand cmd;
private void button1_Click(object sender, EventArgs e)
{
if (textBox3.Text == "")
{
MessageBox.Show("请输入主机地址!");
}
else
{
try
{
string ConStr = "server =" + textBox3.Text.Trim() + ";database =tower;uid = user1;pwd= xaut";
conn = new MySqlConnection(ConStr);
conn.Open();
if (conn.State == ConnectionState.Open)
{
label4.Text = "成功";
}
}
catch
{
MessageBox.Show("连接失败!");
}
}
} private void button3_Click(object sender, EventArgs e)
{
if (conn.State == ConnectionState.Open)
{
cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from " + textBox4.Text.Trim();
cmd.CommandType = CommandType.Text;
int i = Convert.ToInt32(cmd.ExecuteScalar()) + 1;
label5.Text = "有" + i.ToString() + "条记录";
}
}
}
}
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace MyPro_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
}
MySqlConnection conn;
MySqlCommand cmd;
private void button1_Click(object sender, EventArgs e)
{
if (textBox3.Text == "")
{
MessageBox.Show("请输入主机地址!");
}
else
{
try
{
string ConStr = "server =" + textBox3.Text.Trim() + ";database =tower;uid = user1;pwd= xaut";
conn = new MySqlConnection(ConStr);
conn.Open();
if (conn.State == ConnectionState.Open)
{
label4.Text = "成功";
}
}
catch
{
MessageBox.Show("连接失败!");
}
}
} private void button3_Click(object sender, EventArgs e)
{
if (conn.State == ConnectionState.Open)
{
cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from " + textBox4.Text.Trim();
cmd.CommandType = CommandType.Text;
int i = Convert.ToInt32(cmd.ExecuteScalar()) + 1;
label5.Text = "有" + i.ToString() + "条记录";
}
}
}
}
select * from " + textBox4.Text.Trim()
直接在数据库里查询能得到几条数据呢?
执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行。
/// 根据sql语句来获取DataTable.
/// </summary>
/// <param name="sql">sql语句</param>
/// <returns></returns>
public DataTable GetDataTable(string sql)
{
SqlConnection conn = new SqlData().CreateConnection();
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(sql, conn);
adp.Fill(dt);
conn.Close();
return dt; }
mysql中有count吧?
label5.Text = "有" + i.ToString() + "条记录";改成这样试试!