我有一个mysql表调用UIDhold和一个名为UID
的列(主键)。我的值从1-20000开始自动递增。
在我的WPF应用程序中,我有mysql .net库引用并已成功连接到数据库。我想知道的是,在连接到数据库之后,我将如何选择UID(示例; 1),存储该值文本框或字符串变量`,然后从db表中删除该UID?
当我在Mysql cmdline中执行时:
SELECT LAST_INSERT_ID();
我得到0
,但第一个值应为1
。
任何指导都会很棒!
更新:
我已经弄清楚如何选择minium UID,这将是1.但是我不知道如何将它存储在字符串变量/文本框中。 UIDTextBox.Text = myData处的语法错误。 “System.data.datatable类型的值无法转换为字符串。”那么我需要做什么?
VB.Net
Imports MySql.Data.MySqlClient
Imports System.Data
Public Class test1
Dim cmd As New MySqlCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim myData As New DataTable
Dim SQL As String
Dim connStr As String = "Database=;" & _
"Data Source=localhost;" & _
"User Id=;Password=;"
Dim connection As New MySqlConnection(connStr)
connection.Open()
SQL = "SELECT MIN(UID) FROM `UIDhold`"
myCommand.CommandText = SQL
myAdapter.SelectCommand = myCommand
myAdapter.Fill(myData)
UIDTextBox.Text = myData
End Sub
End Class
XAML
<Window x:Class="test1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="test1" Height="300" Width="300">
<Grid>
<Button Content="Sign In" Height="23" HorizontalAlignment="Left" Margin="184,159,0,0" Name="Button1" VerticalAlignment="Top" Width="75" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="120,38,0,0" Name="UIDTextBox" VerticalAlignment="Top" Width="68" />
<Label Content="UID" Height="28" HorizontalAlignment="Left" Margin="58,33,0,0" Name="Label1" VerticalAlignment="Top" />
</Grid>
</Window>
答案 0 :(得分:1)
自动递增可以通过MySQL服务器本身完成。您只需在设置表时进行设置即可。
CREATE TABLE data(
UID MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM;
因此,只要您想将其存储回数据库,如果将值设置为null,它将自动递增。
INSERT INTO animals (name) VALUES
('ssss')
也是你想要做的事(希望我理解正确);但是,如果你想创建数据表,你必须解析每一行,然后使用我认为的while循环添加它。
table.Columns.Add("UID", typeof(int));
table.Columns.Add("name", typeof(string));
using (var varConnection = Locale.sqlConnectOneTimeMySql(Locale.sqlDataConnectionDetailsMySQL))
using (var sqlQuery = new MySqlCommand(preparedCommand, varConnection)) {
using (var sqlQueryResult = sqlQuery.ExecuteReader())
while (sqlQueryResult.Read()) {
//above is basic sql stuff i expect you know
//Here's where you ge thte data
int uid = sqlQueryResult["UID"] is int ? (int)sqlQueryResult["UID"] : 0;
string name = sqlQueryResult["name"].ToString();
// here is where you're outputting to your table
table.Rows.Add(uid,name);
}
}
}