-1

我有一个名为 UIDhold 的 mysql 表和一个名为UID(主键)的列。我的值从 1-20000 自动递增。

在我的 WPF 应用程序中,我有 mysql .net 库参考并已成功连接到数据库。我想知道的是在连接到数据库之后,我将如何选择 UID(例如;1),存储该值文本框或字符串变量`,然后从 db 表中删除该 UID?

当我在 Mysql cmdline 中执行时:

SELECT LAST_INSERT_ID();

我明白0了,但第一个值应该是1

任何指导都会很棒!

更新:

我已经弄清楚如何选择最小 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>
4

1 回答 1

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); 
                }
         }
    }
于 2013-01-11T16:26:48.970 回答