日期:2014-05-17  浏览次数:20869 次

连接数据库小程序求指教
各位好,用C#连接数据库,表中有两列是wav,element。按条件查询时wav能查询到,element不能。程序如下,求指教。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;

namespace database2
{
  class Program
  {
  static void Main(string[] args)
  {
  MySqlConnection conn; // mysql连接 
  MySqlDataAdapter myadp,myadp1; // mysql数据适配器 
  DataSet myds,myds1; // 数据集
  DataTable mytable,mytable1;
  string MyConnectionString;
  MyConnectionString = "server = localhost; uid = root; pwd = mysql; database = spec_line";
  double X = 318.115;
  try
  {
  //打开菜单配置数据库连接 
  conn = new MySqlConnection(); // 实例化数据库连接(instanced) 
  conn.ConnectionString = MyConnectionString; // 配置连接(configured) 
  conn.Open(); // 打开连接(opened) 
  myadp = new MySqlDataAdapter("select * from spec_line where Wav >305.12, conn);
  mytable = new DataTable();
  myds = new DataSet();
  // 填充和绑定数据 
  myadp.Fill(mytable);
  int col = mytable.Columns.Count;
  foreach (DataRow item in mytable.Rows)
  {
  for (int i = 0; i < col; i++)
  {
  Console.Write(item[i].ToString() + " ");
  }
  Console.WriteLine();
  }
   
  myadp1 = new MySqlDataAdapter("select * from spec_line where Element = Ca", conn);
  mytable1 = new DataTable();
  myds1 = new DataSet();
  // 填充和绑定数据 
  myadp1.Fill(mytable1);
  int col1 = mytable1.Columns.Count;
  foreach (DataRow item1 in mytable1.Rows)
  {
  for (int j = 0; j < col1; j++)
  {
  Console.Write(item1[j].ToString() + " ");
  }
  Console.WriteLine();
  }
  Console.ReadKey();
  }

  catch (MySqlException ex)
  {
  switch (ex.Number)
  {
  case 0:
  Console.WriteLine("不能连接到数据库服务器,请联系数据库管理员!"); break;
  case 1045:
  Console.WriteLine("无效的用户名/密码,请重试!"); break;
  case 1049:
  Console.WriteLine("数据库不存在,或数据库名错误"); break;
  default:
  Console.WriteLine(ex.Message); break;
  }
  }
  }
  }
}
谢谢。

------解决方案--------------------
你的参数值是字符,下面的SQL语句里面应该加上左右引号
myadp1 = new MySqlDataAdapter("select * from spec_line where Element = Ca", conn);
=》
myadp1 = new MySqlDataAdapter("select * from spec_line where Element = ‘Ca’", conn);

------解决方案-----------------