我正在使用VS Express 2012,SQL Server 2012.我有一个表(计算机)和两行10列(HaHu_ID,Serial_Number,品牌,型号,操作系统,处理器,硬盘,内存,ST,速度)。< / p>
我一直在这个网站上阅读尽可能多的帖子,因为我可以尝试创建一个SQL Server的vb.net接口。我成功连接它们并将值返回到带有
的DataGridView表SELECT * FROM computers
但是当我尝试其他命令时,如
SELECT * FROM computers
WHERE 'HaHu_ID' = '101'
它返回一个空的DataGridView行!尝试将'HaHu_ID'更改为随机的东西,但它仍然给了我空行。显示正确的列名,但行都是空的。
当我尝试另一个命令“SELECT'HaHu_ID','Brand'FROM computers”时它又回来了:
Column1---|--Column2
-HaHu_ID--|--Brand
-HaHu_ID--|--Brand
列名已更改为“Column1 and column2”,正如您所看到的那样,行填充了列名称!沮丧我尝试了“SELECT'HaHu','Brand_ID'INTER computers'”(我数据库中的非现有列)并返回:
Column1---|--Column2
---HaHu----|--Brand_ID
----HaHu---|--Brand_ID
我回到原来的SELECT * FROM computers
并再次运作了!
这是我的代码:
Dim cs as New SqlConnection...
cs.Open()
'Dim da2 as New SqlDataAdapter("SELECT * FROM computers WHERE 'HaHu_ID' = '101'", cs)
Dim da2 as New SqlDataAdapter("SELECT * FROM computers", cs)
Dim table as New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
da2.Fill(table)
BindingSource1.DataSource = table
dataGrid1.DataSource = BindingSource1
cs.Close()
(我无法复制并粘贴它,因为我现在在另一台计算机上)。因此select * from computers
语句可以完美地运行,但只要我尝试其他内容就不起作用。
为什么?感谢。
答案 0 :(得分:1)
不要在列名称周围加上单引号。在哪里HaHu_ID ='101'是正确的。
答案 1 :(得分:1)
单引号用于指定字符或字符串。以下SQL语句选择字符串'HaHu_ID'和字符串'Brand',并为计算机表中的每条记录返回。由于没有分配别名,服务器返回Column1,Column2等的默认值
SELECT 'HaHu_ID', 'Brand' FROM computers
要转义列名,请使用方括号:
SELECT [HaHu_ID], [Brand] FROM [computers]
答案 2 :(得分:0)
是的,你要比较两个字符串:
SELECT * FROM computers WHERE 'HaHu_ID' = '101'
尝试:
SELECT 'foo' FROM computers WHERE HaHu_ID = '101'
(假设它是字符类型列而不是数字)
答案 3 :(得分:0)
这是你想要做的吗?
SELECT * FROM computers
WHERE col1 = 'HaHu_ID' and col2 = '101'
或
SELECT * FROM computers
WHERE col1 like '%HaHu_ID%' and col2 like '%101%'
如果没有,“SELECT * FROM computers”会为您返回什么?
答案 4 :(得分:0)
Private Sub TxtID_TextChanged(sender as Object,e As EventArgs)处理TxtID.TextChanged
Dim ds As New My_Ticket_MachineDataSet
'连接设置
Dim con As New SqlConnection(“Data Source = LEES-PC; Initial Catalog = My 售票机;集成安全性=真“)
'选择哪一行
Dim com As New SqlCommand(“select * from FareChartTest,TicketPricesID = 3”,con)
com.Parameters.Add(“@ TicketPricesID”,SqlDbType.Int).Value = TxtID.Text
Dim adapter As New SqlDataAdapter(com)
Dim table As New DataTable()
adapter.Fill(表)
If table.Rows.Count() > 0 Then
'which column to select
TextBox4.Text = table.Rows(0)(0).ToString()
' return only 1 row
'which column to select
TextBox3.Text = table.Rows(0)(1).ToString()
Else
MessageBox.Show("NO Data Found")
End If
End Sub