В настоящее время возникают проблемы с удалением / перезаписью из файла

Если вы хотите увидеть, что все это значит, вот удар по всему:

CREATE TABLE `users_partners` (
  `uid` int(11) NOT NULL DEFAULT '0',
  `pid` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`uid`,`pid`),
  KEY `partner_user` (`pid`,`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

Основной ключ основан на обоих столбцах этой таблицы быстрого сравнения. Первичный ключ требует уникальных значений.

Начнем:

INSERT INTO users_partners (uid,pid) VALUES (1,1);
...1 row(s) affected

INSERT INTO users_partners (uid,pid) VALUES (1,1);
...Error Code : 1062
...Duplicate entry '1-1' for key 'PRIMARY'

INSERT IGNORE INTO users_partners (uid,pid) VALUES (1,1);
...0 row(s) affected

INSERT INTO users_partners (uid,pid) VALUES (1,1) ON DUPLICATE KEY UPDATE uid=uid
...0 row(s) affected

обратите внимание, что выше сохранена слишком большая дополнительная работа, установив столбец равным самому себе, никакого обновления на самом деле не требуется

REPLACE INTO users_partners (uid,pid) VALUES (1,1)
...2 row(s) affected

, а теперь несколько тестов с несколькими строками:

INSERT INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4)
...Error Code : 1062
...Duplicate entry '1-1' for key 'PRIMARY'

INSERT IGNORE INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4)
...3 row(s) affected

в консоли не было создано никаких других сообщений, и теперь в этих таблицах теперь есть эти 4 значения. Я удалил все, кроме (1,1), чтобы я мог протестировать с одного и того же игрового поля

INSERT INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4) ON DUPLICATE KEY UPDATE uid=uid
...3 row(s) affected

REPLACE INTO users_partners (uid,pid) VALUES (1,1),(1,2),(1,3),(1,4)
...5 row(s) affected

Итак, у вас оно есть. Так как все это было сделано на свежем столе с почти отсутствием данных, а не на производстве, времена для выполнения были микроскопическими и неактуальными. Любой, кто имеет данные в реальном мире, будет более чем рад внести свой вклад.

-2
задан Mr_monkog 20 January 2019 в 20:16
поделиться

1 ответ

Кто решил, что этот текстовый файл будет отформатирован с полями фиксированной длины? Всего этого обрезания и дополнения можно избежать с помощью простого файла с разделителями-запятыми или XML-файла или базы данных, которой он действительно принадлежит. Код не проверен. Комментарии и объяснения в строке.

'I assume you have a class that looks something like this
'This uses automatic properties to save you having to
'type a getter, setter and backer field (the compiler adds these)
Public Class Department
    Public Property DepartmentID As Integer
    Public Property DepartmentHead As String
    Public Property DepartmentName As String
    Public Property DepartmentBudget As Decimal
End Class


Private Sub BtnBillDept_Click(sender As Object, e As EventArgs) Handles BtnBillDept.Click
    Dim DepartmentStore As New Department
    'Drag an OpenFileDialog from the ToolBox to your form
    'It will appear in the lower portion of the design window
    Dim MyFilePath As String = ""
    OpenFileDialog1.Title = "Select OrderDetails.Txt"
    If OpenFileDialog1.ShowDialog = DialogResult.OK Then
        MyFilePath = OpenFileDialog1.FileName
    End If
    Dim Order() As String = File.ReadAllLines(MyFilePath)
    'Changed data type, you use OrderID as an index for the Order array so it must be an Integer
    Dim OrderID As Integer
    'TryParse will check if you have a valid interger and fill OrderID variable
    If Not Integer.TryParse(TxtOrderID.Text, OrderID) Then
        MessageBox.Show("Please enter a valid Order ID.")
        Return
    End If
    'EDIT per comment by Codexer 
    If OrderID > Order.Length - 1 Then
        MessageBox.Show("Order Number is too high")
        Return
    End If

    Dim AmountDue As Decimal
    If Decimal.TryParse(TxtAmountDue.Text, AmountDue) Then
        MessageBox.Show("Please enter a valid Amount Due")
        Return
    End If
    'I hope you realize that the first index in Order is zero
    'Mid is an old VB6 method around for compatibility
    'Use the .net Substring (startIndex As Integer, length As Integer)
    'The indexes in the string start with zero
    Dim DeptID As Integer = CInt(Order(OrderID).Substring(5, 4).Trim) '(Trim(Mid(Order(OrderID), 5, 4)))
    OpenFileDialog1.Title = "Select DepartmentDetails.txt"
    If OpenFileDialog1.ShowDialog = DialogResult.OK Then
        MyFilePath = OpenFileDialog1.FileName
    End If
    Dim DepartmentDetails() As String = File.ReadAllLines(MyFilePath)
    Dim DepartmentBudget As Decimal = CDec(DepartmentDetails(DeptID).Substring(35, 6).Trim) '(Trim(Mid(DepartmentDetails(DeptID), 35, 6)))
    'You don't need to format anything until you want to display it
    'Dim FormattedBudget As String = FormatCurrency(DepartmentBudget, 2)
    'A MessageBox returns a DialogResult
    Dim YesNo As DialogResult
    Dim sw As New StreamWriter(MyFilePath, True)
    'Shorcut way to write DepartmentBudget - AmountDue
    DepartmentBudget -= AmountDue
    'Set the property in the class with the proper data type
    DepartmentStore.DepartmentID = DeptID
    'Then prepare a string for the writing to the fil
    Dim PaddedID = CStr(DeptID).PadLeft(4)
    'The .net replacement for LSet is .PadLeft
    DepartmentStore.DepartmentHead = DepartmentDetails(DeptID).Substring(5, 20).Trim.PadLeft(20)
    DepartmentStore.DepartmentName = DepartmentDetails(DeptID).Substring(25, 10).Trim.PadLeft(20)
    'Set the property in the class with the proper data type
    DepartmentStore.DepartmentBudget = DepartmentBudget
    'Then prepare a string for the writing to the fil
    Dim PaddedBudget = CStr(DepartmentBudget).PadLeft(9)
    sw.WriteLine(PaddedID & DepartmentStore.DepartmentHead & DepartmentStore.DepartmentName & PaddedBudget)
    sw.Close()
    '***********************Having Problems Here***********************
    'This is using the path from the most recent dialog
    DepartmentDetails = File.ReadAllLines(MyFilePath)
    'Here you are changing the value of one of the elements in the DepartmentDetails array
    DepartmentDetails(DeptID) = ""
    'Public Shared Sub WriteAllLines (path As String, contents As String())
    'The string "DepartmentDetails" is not a path
    File.WriteAllLines(MyFilePath, DepartmentDetails)
    '************************Having Problems Here**************************
    YesNo = MessageBox.Show("Department has been billed. Would you like to delete the bill?", "Delete Bill?", MessageBoxButtons.YesNo)
    If YesNo = DialogResult.Yes Then

    End If
End Sub
0
ответ дан Mary 20 January 2019 в 20:16
поделиться
Другие вопросы по тегам:

Похожие вопросы: