菜鸟问题
textBox2输入的是“2013-03-04”日期格式,执行下面代码报错“从字符串向 datetime 转换时失败。”求解!if (textBox1.Text.Trim() != "" && textBox2.Text.Trim() != "")
{
string str1 = textBox1.Text.Trim();
String strCom = "select * from 123 where NAME= 'str1' and DATE= 'textBox2.Text' ";
DataSet ds = new DataSet();
SqlDataAdapter myCommand = new SqlDataAdapter(strCom, con);
myCommand.Fill(ds, "123 ");
if (ds.Tables["123 "].Rows.Count > 0)
{
dataGridView1.Visible = true;
dataGridView1.DataSource = ds.Tables[0];
}
else
{
dataGridView1.DataSource = null;
MessageBox.Show("没有查到适合条件的数据!");
}
} --------------------编程问答-------------------- 你这SQL里面要传给日期参数的值实际上是传成了字符串'textBox2.Text' ,而不是它里面的日期值 --------------------编程问答-------------------- 需要怎么修改了! --------------------编程问答-------------------- namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string time = "2013-4-14";
string[] timed = time.Split('-');
int[] timer = new int[3];
int i = 0;
foreach (string item in timed)
{
timer[i++] = int.Parse(item);
}
DateTime dt = new DateTime(timer[0], timer[1], timer[2]);
Console.WriteLine(dt.ToString());
while (true) ;
}
}
} --------------------编程问答-------------------- 顶!顶!顶! --------------------编程问答-------------------- String strCom = "select * from 123 where NAME= 'str1' and DATE= 'textBox2.Text' ";
你什么数据库?
SQL Server的话,改成
String strCom = "select * from 123 where NAME= 'str1' and DATE= '"+textBox2.Text+"'";
Oracle 的话
String strCom = "select * from 123 where NAME= 'str1' and to_char(DATE,"yyyy-MM-dd")= '"+textBox2.Text+"'"; --------------------编程问答-------------------- String strCom = "select * from 123 where NAME= '"+str1+"' and DATE= '"+textBox2.Text+"'";
只改该句即可,就是字符串的拼接 --------------------编程问答--------------------
忘记说了,红色部分肯定错了 --------------------编程问答-------------------- 给你个思路你试一下,用 "@"占位符,然后再添加Parameter的方式(注意,添加参数前先清楚参数),
应该是像 1 楼说的,因为在SQl中,没有像 CSharp的WinForm那样textBox2.Text取得 字符串的值。 --------------------编程问答--------------------
版主的这样貌似也行,不过最好还是不要用直接拼接的方式吧。防止安全。 --------------------编程问答-------------------- 防止恶意输入! --------------------编程问答--------------------
我只是指出他的问题,可以用参数化查询 --------------------编程问答--------------------
补充:.NET技术 , C#