Is there any way to get the table adapter to insert the values already in the dataset I pass it when inserting new rows?
I am synchronising two databases and this would be useful.
Here is currently how I am trying to do it but it auto increments and creates new identity values.
Dim dAdapterConstraints As New SqlClient.SqlDataAdapter("SELECT * FROM " + Tablename, _oConn)
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(dAdapterConstraints)
builder.QuotePrefix = "["
builder.QuoteSuffix = "]"
dAdapterConstraints.InsertCommand = builder.GetInsertCommand
Dim insertcommandstr As String = dAdapterConstraints.InsertCommand.CommandText.Substring(0, dAdapterConstraints.InsertCommand.CommandText.IndexOf("(") + 1) + " [" + Primarykey + "], " + dAdapterConstraints.InsertCommand.CommandText.Substring(dAdapterConstraints.InsertCommand.CommandText.IndexOf("(") + 1, dAdapterConstraints.InsertCommand.CommandText.Length - (dAdapterConstraints.InsertCommand.CommandText.IndexOf("(") + 1))
insertcommandstr = insertcommandstr.Replace("#p1", "#po1, #p1")
dAdapterConstraints.InsertCommand.Parameters.Add("#po1", getdbtype(dataset.Tables(0).Columns(Primarykey).DataType), dataset.Tables(0).Columns(Primarykey).MaxLength, Primarykey)
insertcommandstr = "SET IDENTITY_INSERT [" + Tablename + "] ON " + insertcommandstr + " SET IDENTITY_INSERT [" + Tablename + "] OFF"
dAdapterConstraints.InsertCommand.CommandText = insertcommandstr
dataset.EnforceConstraints = False
' opens connection
'fills dataset with results
Try
For Each row As DataRow In dataset.Tables(0).Rows
row.SetAdded()
Next
dAdapterConstraints.Update(dataset)
Catch ex As Exception
_oConn.Close()
MsgBox("Could not execute query on server database," + ex.ToString + ";Updating and inserting")
Return False
End Try
Related
I'm making a script to help me out filling in a MySQL table. It basically loops through every year group and set and makes a class for their subject. For Example : Year Group 8, Set 4, English would be 84En etc etc. I made it so it loops through an ArrayList and changes some variables but I can't seem to get it to work.
I don't really know what to try to be honest because I've checked over it and I don't know if I'm blind but I don't see any errors.
Dim subjects As New ArrayList
subjects.Add("English")
subjects.Add("Welsh")
subjects.Add("French")
subjects.Add("Maths")
subjects.Add("Science")
subjects.Add("History")
subjects.Add("Geography")
subjects.Add("Pe")
subjects.Add("Re")
subjects.Add("Tutorial")
subjects.Add("Music")
subjects.Add("Drama")
subjects.Add("Technology")
subjects.Add("It")
subjects.Add("Art")
Dim upsubjects As New ArrayList
upsubjects.Add("English")
upsubjects.Add("Welsh")
upsubjects.Add("Physics")
upsubjects.Add("Biology")
upsubjects.Add("Chemistry")
upsubjects.Add("French")
upsubjects.Add("Maths")
upsubjects.Add("Science")
upsubjects.Add("History")
upsubjects.Add("Music")
upsubjects.Add("Technology")
upsubjects.Add("It")
Dim year As Integer = 7
Dim setting As Integer = 8
Dim done As Boolean = False
Dim cmd As MySqlCommand
While done = False
For Each subject As String In subjects
If year = 9 And setting = 8 Then
cmd = New MySqlCommand("INSERT INTO classes (`classid`, `class`) VALUES ('" + year + setting + subject.Substring(2, (subject.Length - 2)).ToUpper + "', '" + subject.Substring(2, (subject.Length - 2)) + "')", conn)
cmd.ExecuteNonQuery()
setting = 1
End If
If setting = 8 And Not year = 9 Then
cmd = New MySqlCommand("INSERT INTO classes (`classid`, `class`) VALUES ('" + year + setting + subject.Substring(2, (subject.Length - 2)).ToUpper + "', '" + subject.Substring(2, (subject.Length - 2)) + "')", conn)
cmd.ExecuteNonQuery()
setting = 1
year = year + 1
Else
cmd = New MySqlCommand("INSERT INTO classes (`classid`, `class`) VALUES ('" + year + setting + subject.Substring(2, (subject.Length - 2)).ToUpper + "', '" + subject.Substring(2, (subject.Length - 2)) + "')", conn)
cmd.ExecuteNonQuery()
setting = setting + 1
End If
Next
For Each subject As String In upsubjects
If year = 11 And setting = 8 Then
cmd = New MySqlCommand("INSERT INTO classes (`classid`, `class`) VALUES ('" + year + setting + subject.Substring(2, (subject.Length - 2)).ToUpper + "', '" + subject.Substring(2, (subject.Length - 2)) + "')", conn)
cmd.ExecuteNonQuery()
setting = 1
done = True
End If
If setting = 8 And Not year = 11 Then
cmd = New MySqlCommand("INSERT INTO classes (`classid`, `class`) VALUES ('" + year + setting + subject.Substring(2, (subject.Length - 2)).ToUpper + "', '" + subject.Substring(2, (subject.Length - 2)) + "')", conn)
cmd.ExecuteNonQuery()
setting = 1
year = year + 1
Else
cmd = New MySqlCommand("INSERT INTO classes (`classid`, `class`) VALUES ('" + year + setting + subject.Substring(2, (subject.Length - 2)).ToUpper + "', '" + subject.Substring(2, (subject.Length - 2)) + "')", conn)
cmd.ExecuteNonQuery()
setting = setting + 1
End If
Next
End While
I'm not getting any error messages, the form just loads (when the code is supposed to execute) and does nothing. Refreshed my MySQL database and nothing still. Any ideas on how to fix this??
If you're concatenating numeric values setting and year into your query string, don't you need to convert them to strings before you do so, with something like CStr()?
Not getting an error suggests to me that the code isn't being executed, but as others said in the comments, you can soon add a 'Stop' to check that.
Also, have a read up on "Database normalisation", with regard to combining various values into a single column in the table, think about how you're going to retrieve that information and how much easier it will be if you keep it separate.
Hello Good Afternoon I have a program in VB.Net that will Input data
from textboxes into Access Database here is sample image
This is the code I am using and it gives me an error
m = TextBox1.Text
b = "'" + TextBox2.Text + "'"
x = "'" + TextBox3.Text + "'"
d = TextBox4.Text
n = "'" + TextBox5.Text + "'"
Dim s2 As String
s2 = "insert into users2 ( num , name1 , pass , add , phone ) " & " values ( " + m + " , " + n + " , " + b + " , " + x + " , " + d + " ) "
Dim cmd2 As New OleDbCommand(s2, con)
cmd2.ExecuteNonQuery()
Looking forward that someone will enlighten my problem since its im starting to program.
TYSM for future help
You need to encapsulate values you want to insert into ''
. "values('" + m + "', '" + ...
2 I don't understand & operator between two parts of query in the beginning
I have a table in csv file (with an ID as numeric).
I manually uploaded the information from the file to a SQL Server data table (creating my ID column as numeric).
But, I want to recreate my ID column as autonumeric ID column that continue the number with the latest entry.
Example: the table have the ID 1, 5, 10. I want to recreate the auto-incremental (IDENTITY) ID column (leaving my old ID's) and next row insertion continue with ID 11.
I suppose that doesn't exists a single method to achieve this. But I want to know the steps that I should follow.
Here is a script to give you an idea of one way you can do it.
IF OBJECT_ID('DELETEME.dbo.Tbl') IS NOT NULL
BEGIN
DROP TABLE Tbl
END
IF OBJECT_ID('DELETEME.dbo.stageTbl') IS NOT NULL
BEGIN
DROP TABLE stageTbl
END
CREATE TABLE Tbl (
ID INT
,A CHAR(1)
)
INSERT INTO Tbl VALUES (1,'A'),(2,'B'),(10,'C')
SELECT *
FROM
Tbl
EXEC sp_rename 'DELETEME.dbo.Tbl', 'stageTbl', 'OBJECT'
--renames original table
--create script for the new table
CREATE TABLE Tbl (
ID INT NOT NULL IDENTITY(1,1)
,A CHAR(1)
)
--have to set IDENTITY_INSERT on to insert the ID into an IDENTITY column
SET IDENTITY_INSERT Tbl ON
INSERT INTO Tbl (ID, A)
SELECT ID, A
FROM
stageTbl
SET IDENTITY_INSERT Tbl OFF
DROP TABLE stageTbl
--drops original table
DBCC CHECKIDENT('Tbl', RESEED, 222)
--sets the number you want to with next if you set as 222 the next identity will be 223
INSERT INTO Tbl (A) VALUES ('D')
SELECT *
FROM
Tbl
Basic Steps
Renames original Table (if you want your new table to be the same name as the old, I like to rename first due to auto generated names of constraints etc on the new table)
Create the New table with the Column as an Identity column
Turn on IDENTITY_INSERT
Select all records from the old table into the new one
Turn off IDENTITY_INSERT
You don't have to but you can RESSED the identity to start with whatever number you want otherwise SQL-server will automatically do this based on the greatest ID value.
Drop the original table that you renamed
Thanks to Matt to help me out with the original question.
I want to share a C# method that I used to automate all the necessary steps:
-- Disclaimer: the use of this is my class that connects with MS SQL Server, used to read a SELECT sentence (And returns a DataTable) and Execute SQL Queries, etc. Hope someone could find this code helpfully (AS-IS) --
/// <summary> Recreate an ID with auto-incremental when the table has the ID without this option.
/// <para>Automatically will rename the original table to TABLENAME_TO_DELETE (The process will require copy and recreate the table, then the process will duplicate the information) </para></summary>
/// <param name="strTable">SQL table</param>
/// <param name="strId">ID column</param>
public string recreateIdentityColumn(string strTable, string strId)
{
string strLog = "Table: {0} - ID: {1}".fwFormat(strTable, strId);
string strNewTable = strTable + "_" + fw.rnd(1, 1000).ToString() + fw.rnd(5000, 10000);
DataTable dtTable = this.fillDataTable("SELECT COLUMN_NAME, DATA_TYPE, NUMERIC_PRECISION, NUMERIC_SCALE " +
"FROM Information_SCHEMA.COLUMNS " +
"WHERE TABLE_NAME = '" + strTable + "'");
if (!dtTable.fwHasData()) throw new Exception("The current table '" + strTable + "' doesn't exists");
DataRow[] drIdInfo = dtTable.Select("COLUMN_NAME = '" + strId + "'");
if (!drIdInfo.fwHasData()) throw new Exception("The ID column '" + strId + "' doesn't exists in the table '" + strTable + "'");
string strIdType = "";
string strColumns = "";
strIdType = drIdInfo[0]["DATA_TYPE"].fwEmpty("");
if (strIdType.fwContains("decimal"))
strIdType += "({0}, {1})".fwFormat(drIdInfo[0]["NUMERIC_PRECISION"].ToString(), drIdInfo[0]["NUMERIC_SCALE"].ToString());
strLog += "\r\nID DataType: " + strIdType;
foreach (DataRow drInfo in dtTable.Rows)
strColumns += ",[" + drInfo["COLUMN_NAME"].ToString() + "]";
strId = "[" + strId.TrimStart('[').TrimEnd(']') + "]";
strColumns = strColumns.TrimStart(',');
strLog += "\r\nColumns: " + strColumns;
try
{
// Rule 1: Clone the table (Only the structure)
this.executeQuery("SELECT TOP 0 * INTO " + strNewTable + " FROM " + strTable);
// Rule 2: Remove the ID from the clone table
this.executeQuery("ALTER TABLE " + strNewTable + " DROP COLUMN " + strId);
// Rule 3: Add the ID column with the identity property
this.executeQuery("ALTER TABLE " + strNewTable + " ADD " + strId + " " + strIdType + " IDENTITY(1,1)");
// Rule 4: Allow manual insertion of ID in the identity column
this.executeQuery("SET IDENTITY_INSERT " + strNewTable + " ON");
// Rule 5: Copy the rows into the table
int intTotalRows = this.rowCount(strTable);
int intTotalNewRows = this.executeQuery("INSERT INTO " + strNewTable + "(" + strColumns + ") " +
"SELECT " + strColumns + " FROM " + strTable);
strLog += "\r\nOriginal rows {0} - New rows {1}".fwFormat(intTotalRows.ToString(), intTotalNewRows.ToString());
// Rule 6: Return the insertion of identity rows to a normal state
this.executeQuery("SET IDENTITY_INSERT " + strNewTable + " OFF");
// Rule 7: Rename the table with NO IDENTITY as OLD and rename the table with INDENTITY ID as NEW/ACTUAL
this.executeQuery("EXEC sp_rename '" + strTable + "', '" + strTable + "_TO_DELETE', 'OBJECT'");
this.executeQuery("EXEC sp_rename '" + strNewTable + "', '" + strTable + "', 'OBJECT'");
strLog += "\r\nProcess run without problems";
return strLog;
}
catch (Exception ex)
{
strLog += "\r\nException occur";
throw ex;
}
}
I have two tables in my database - MPRS and ALL_SSC. I want to update the ALL_SSC table with data from MPRS and in Access (where I test my SQL) it works.
However, when I run it in my VB 2010 program on the SQL Server database, it says table MPRS already exists.
I know it does! I'm not trying to create it. I'm updating FROM it... any ideas where this SQL is wrong?
SQL = "UPDATE ALL_SSC LEFT JOIN MPRS ON MPRS.MPAN = ALL_SSC.MPAN1 SET ALL_SSC.PC1 = Format([mprs].[pc],'00'), ALL_SSC.MSPCDC1 = Mid([mprs].[PC_EFD],7,4) & Mid([mprs].[PC_EFD],4,2) & Mid([mprs].[PC_EFD],1,2), ALL_SSC.MTSC1 = [mprs].[MTC], ALL_SSC.MSMCDC1 = Mid([mprs].[MTC_EFD],7,4) & Mid([mprs].[MTC_EFD],4,2) & Mid([mprs].[MTC_EFD],1,2), ALL_SSC.LLF1 = [mprs].[LLF], ALL_SSC.SUPPLIER1 = [mprs].[SUPPLIER], ALL_SSC.REGI1 = Mid([mprs].[SSD],7,4) & Mid([mprs].[SSD],4,2) & Mid([mprs].[SSD],1,2), ALL_SSC.ENG_STATUS1 = 0 WHERE (((ALL_SSC.MPAN1) Is Not Null) AND ([mprs].[ENERG_STATUS]='E'));"
cmd = New SqlCommand(sSQL, cNN)
Try
Try
If cNN.State <> ConnectionState.Open Then
cNN.Open()
End If
Catch exCnn As Exception
MsgBox(exCnn.Message)
End Try
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Cannot continue. " & ex.Message)
Exit Sub
End Try
You have accidentally used variable "sSQL" when you meant to use "SQL".
Yet another example of why meaningful variable names are important.
The correct syntax for a JOIN with UPDATE in SQL Server is:
UPDATE a
SET PC1 = . . .
FROM ALL_SSC a LEFT JOIN
MPRS m
ON m.MPAN = a.MPAN1
WHERE . . .;
That is, you need a FROM clause and it comes after the SET.
Thanks Gordon for your help. One or two other changes needed to move from Access SQL to SQL Server, but this is the SQL i ended up with working in SQL Server.
UPDATE a
SET
a.PC1 = '0' + m.[pc],
a.MSPCDC1 = substring(m.[PC_EFD],7,4) + substring(m.[PC_EFD],4,2) + substring(m.[PC_EFD],1,2),
a.MTSC1 = m.[MTC],
a.MSMCDC1 = substring(m.[MTC_EFD],7,4) +substring(m.[MTC_EFD],4,2) + substring(m.[MTC_EFD],1,2),
a.LLF1 = m.[LLF],
a.SUPPLIER1 = m.[SUPPLIER],
a.REGI1 = substring(m.[SSD],7,4) + substring(m.[SSD],4,2) + substring(m.[SSD],1,2),
a.ENG_STATUS1 = 0
FROM [myDataBase].[dbo].ALL_SSC a LEFT JOIN
[myDataBase].[dbo].MPRS m
ON m.MPAN = a.MPAN1
WHERE (((a.MPAN1) Is Not Null) AND (m.[ENERG_STATUS]='E'));
However, When I execute the exact same code on the database via VB 2010, I get the same failure message. This is the vb code
For iMPAN As Integer = 1 To 3
'mpan - energised
SQL = "UPDATE a SET a.PC" + iMPAN.ToString + " = '0' + m.[pc], a.MSPCDC" + iMPAN.ToString + " = substring(m.[PC_EFD],7,4) + substring(m.[PC_EFD],4,2) + substring(m.[PC_EFD],1,2), a.MTSC" + iMPAN.ToString + " = m.[MTC], a.MSMCDC" + iMPAN.ToString + " = substring(m.[MTC_EFD],7,4) +substring(m.[MTC_EFD],4,2) + substring(m.[MTC_EFD],1,2), a.LLF" + iMPAN.ToString + " = m.[LLF], a.SUPPLIER" + iMPAN.ToString + " = m.[SUPPLIER], a.REGI" + iMPAN.ToString + " = substring(m.[SSD],7,4) + substring(m.[SSD],4,2) + substring(m.[SSD],1,2), a.ENG_STATUS" + iMPAN.ToString + " = 0 FROM ALL_SSC a LEFT JOIN MPRS m ON m.MPAN = a.MPAN1 WHERE (((a.MPAN" + iMPAN.ToString + ") Is Not Null) AND (m.[ENERG_STATUS]='E'));"
Debug.Print(SQL)
cmd = New SqlCommand(sSQL, cNN)
Try
Try
If cNN.State <> ConnectionState.Open Then
cNN.Open()
End If
Catch exCnn As Exception
MsgBox(exCnn.Message)
End Try
cmd.ExecuteNonQuery()
Catch ex As Exception
Debug.Print(ex.Message)
MsgBox("Cannot continue. " & ex.Message)
Exit Sub
End Try
Next
In c# Windows Forms:
I'm having trouble adding a sql query result as text to a ToolStripMenuItem.Text.
The ToolStripMenuItem title should be, the company + how many orders there are in the sql table for this company which should update every x secounds.
Every 5 seconds it adds the query result to the text. My problem is that is "adds" it.
After the first 5 seconds it looks OK "rexton 1" but 5 seconds after it shows "rexton 1 1" and so on...
Here is my code:
//Rexton ordre klar til bestilling
SqlConnection con = new SqlConnection(#"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
SqlCommand command = con.CreateCommand();
command.CommandText = "SELECT COUNT(*) from bestillinger WHERE firma = #rexton and udlevering BETWEEN #date and #dateadd";
command.Parameters.AddWithValue("#bernafon", "Bernafon");
command.Parameters.AddWithValue("#gn_resound", "GN Resound");
command.Parameters.AddWithValue("#oticon", "Oticon");
command.Parameters.AddWithValue("#phonak", "Phonak");
command.Parameters.AddWithValue("#rexton", "Rexton");
command.Parameters.AddWithValue("#siemens", "Siemens");
command.Parameters.AddWithValue("#widex", "Widex");
con.Open();
command.ExecuteNonQuery();
string result = command.ExecuteScalar().ToString();
con.Close();
if (result != "0")
{
rextonToolStripMenuItem.Text = rextonToolStripMenuItem.Text + " " + result;
rextonToolStripMenuItem.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF1919");
}
it is because you are setting rextonToolStripMenuItem.Text to rextonToolStripMenuItem.Text + " " + result which is appending to previous text
either set text to blank and set it again or just say
rextonToolStripMenuItem.Text = "rexton " + result