I'm making a successfull Insert into the table, but for some reason the fields are in a messed up position. Working on Visual Studio 2012 C# with an MS Access Database 2010.
(Don't have enough rep to post imagens directly so please bear with the links)
This is what the table structure is like (Sorry but can't post more than 2 links)
( column = fieldtype):
Codigo = text
Data saida (aka #data) = date/hour
Entidade = text
Data Ent = data/hour
GT Ent = text
Estado = text
GT saida = text
observacaoes = text
requisitante = number
certificado = text
resultado = text
selecionar = Yes/No
tipo int = text
This is a good example in the table of a correct row like row Good Row
This is a the row I'm getting with the INSERT Messed up Row
This is how I make the INSERT
OleDbCommand cmd = l.CreateCommand();
cmd.Parameters.Add(new OleDbParameter("#codigo", cal.CodEtiq.ToString()));
cmd.Parameters.Add(new OleDbParameter("#data", cal.Data));
cmd.Parameters.Add(new OleDbParameter("#entidade", cal.EntidadeCal));
cmd.Parameters.Add(new OleDbParameter("#observacao", cal.Observacao));
cmd.Parameters.Add(new OleDbParameter("#certificado", cal.Certificado));
cmd.Parameters.Add(new OleDbParameter("#resultado", cal.Resultado));
cmd.Parameters.Add(new OleDbParameter("#selecionar", cal.Selecionar));
cmd.CommandText = "INSERT INTO [Movimento Ferramentas] VALUES (#codigo, #data , #entidade, null, null, 'Calibração', null, #observacao, null, #certificado, #resultado, #selecionar , null)";
result = cmd.ExecuteNonQuery();
What am I doing wrong here?
Since you haven't specified the columns in your INSERT statement, It is inserting values on the bases of column orders in table. Not really sure what is your actual column order, But you can fix your issue by specifying your columns in INSERT statement.
cmd.CommandText = "INSERT INTO [Movimento Ferramentas] "+
"(Codigo , [Data saida], ...............) " + // columns
"VALUES (#codigo, #data , #entidade, null, null, 'Calibração', null, #observacao, null, #certificado, #resultado, #selecionar , null)";
Related
According to my question with weird problem specified here how to fix
System.Data.SqlClient.SqlException: String or binary data would be truncated in table
My problem is, that if I am saving new problem into the database, its ID is always set to 0 (I checked this out in debugging), which then throws
System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Alert__Problem_I__17F790F9". The conflict occurred in database "SmartOne", table "dbo.Problem", column 'id'
But in SQL Server Management Studio, the ID is set correctly (ID is defined as an Identity column).
Where both I am using is in my question mentioned below. Thanks for any ideas or advice.
Method that saves Problem:
public void Save(Problem element)
{
using (SqlConnection conn = new SqlConnection(DatabaseSingleton.connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO Problem VALUES " +
"(#nameOfAlert, #value, #result, #message_ID) ", conn))
{
command.Parameters.Add(new SqlParameter("#nameOfAlert", element.NameOfAlert));
command.Parameters.Add(new SqlParameter("#value", (int)element.Value));
command.Parameters.Add(new SqlParameter("#result", (int)element.Result));
command.Parameters.Add(new SqlParameter("#message_ID", element.Message_Id));
command.ExecuteNonQuery();
command.CommandText = "Select ##Identity";
}
conn.Close();
}
}
Method that saves an Alert:
public void Save(Alert element)
{
using (SqlConnection conn = new SqlConnection(DatabaseSingleton.connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO [Alert] VALUES (#message_ID, #date, #email, #AMUser_ID, #Problem_ID) ", conn))
{
command.Parameters.Add(new SqlParameter("#message_ID", element.Id_MimeMessage));
command.Parameters.Add(new SqlParameter("#date", element.Date));
command.Parameters.Add(new SqlParameter("#email", element.Email));
command.Parameters.Add(new SqlParameter("#AMUser_ID", element.User_ID));
command.Parameters.Add(new SqlParameter("#Problem_ID", element.Problem_ID));
command.ExecuteNonQuery();
command.CommandText = "Select ##Identity";
}
conn.Close();
}
}
SQL Scheme
CREATE TABLE [dbo].[Alert](
[id] [int] IDENTITY(1,1) NOT NULL,
[message_ID] [varchar](100) NOT NULL,
[date] [datetime] NOT NULL,
[email] [varchar](50) NOT NULL,
[AMUser_ID] [int] NOT NULL,
[Problem_ID] [int] NOT NULL);
//Where is ID, it means FK ID
CREATE TABLE [dbo].[Problem](
[id] [int] IDENTITY(1,1) NOT NULL,
[nameOfAlert] [varchar](50) NOT NULL,
[Value_ID] [int] NOT NULL,
[Result_ID] [int] NOT NULL,
[message_ID] [varchar](100) NOT NULL);
One problem might be that you're never actually getting back the inserted IDENTITY value from your first insert - thus you aren't using any valid ProblemId value for your second insert.
Try something like this:
public void Save(Problem element)
{
using (SqlConnection conn = new SqlConnection(DatabaseSingleton.connString))
{
conn.Open();
// define INSERT query - I'd *strongly* recommend specifying all
// columns you're inserting into!
// Also: run the "SELECT SCOPE_IDENTITY()" right after the INSERT
string insertQry = "INSERT INTO dbo.Problem(NameOfAlert, Value, Result, MessageId) " +
"VALUES (#nameOfAlert, #value, #result, #message_ID); " +
"SELECT SCOPE_IDENTITY();";
using (SqlCommand command = new SqlCommand(insertQry, conn))
{
// also here: define the *datatype* of the parameter, and use
// .Value = to set the value.
// Since you haven't shown what the table looks like, I'm just
// **guessing** the datatype and max length for the string parameters - adapt as needed!
command.Parameters.Add("#nameOfAlert", SqlDbType.VarChar, 100).Value = element.NameOfAlert;
command.Parameters.Add("#value", SqlDbType.Int).Value = (int)element.Value;
command.Parameters.Add("#result", SqlDbType.Int).Value = (int)element.Result;
command.Parameters.Add("#message_ID", SqlDbType.VarChar, 100).Value = element.Message_Id;
// since your statement now returns the ID value - use "ExecuteScalar"
var returnedValue = command.ExecuteScalar();
if (returnedValue != null)
{
// if a value was returned - convert to INT
int problemId = Convert.ToInt32(returnedValue);
}
}
conn.Close();
}
}
Now, in case the INSERT works, you get back the ProblemId value from the identity column, and you can now use this in your second insert as value for the #ProblemId parameter.
For saving the id into other table, you have to complete the insertion first. if the insertion is not completed then you can not get the problem id (if it is the primary key, which is supposed to be returned by saving the datas). Only after saving the data to the table, you are going to have the problem id then you can use it as FK in the same method.
if i say, there is two table and you are going to use the first table primary key in the second table as FK. Then you need to complete the first table row insertion. after excuting the query for the first table, you will get the primary key of that row and you can use easily in the second table as FK.
i have simple table item and a text box textbox1 now i want to show max value in textbox i am using the command but code not work
item table: CREATE TABLE TableItem( ItemId NUMBER(10) NOT NULL,
ItemName VARCHAR2(40) NOT NULL, UnitId NUMBER(10) NOT NULL,
CategoryId NUMBER(10) NOT NULL, ItemStatus NUMBER(1) NOT NULL,
SupplierId NUMBER(10)NOT NULL );
and item table insert data:
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(01,'Product-1',21,10,1,51);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(02,'Product-2',22,11,1,52);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(03,'Product-3',23,12,1,53);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(04,'Product-4',24,14,1,53);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(05,'Product-5',21,12,1,53);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(06,'Product-5',23,12,1,52);
now i need max value of itemid
con.Open();
try
{
OleDbCommand cmd4 = new OleDbCommand("SELECT MAX(ItemId) FROM TableItem", con);
textBoxInsert.Text = cmd4.ExecuteScalar().ToString();
}
finally
{
}
con.Close();
You need to create a data adapter, it will fetch your SQL in your database based on your connection. After that you will get a table as result, so you just need to add it to your DataTable and get the rows. There is more interesting implementations, but with this code you can see if it everything is working fine, I've implemented a MySQL version like this:
DataTable _datatable = new DataTable();
MySQLDataAdapter _adapter = new MySQLDataAdapter("SELECT * FROM TEST_TABLE", connection)
_adapter.Fill(_datatable);
myTextBox.Text = _datatable.Rows[0]["ID"].ToString();
On your case, you just need to replace MySQLDataAdapter with OracleDataAdapter, from OracleClient
Reference:
https://msdn.microsoft.com/pt-br/library/system.data.oracleclient.oracledataadapter(v=vs.110).aspx
It is simple. We took the double result for the number we will get in the database.
using (MySqlCommand cmd = new MySqlCommand("SELECT MAX(ItemId) FROM TableItem", con))
{
con.Open();
double result = (Convert.ToDouble(cmd.ExecuteScalar()));
textBoxInsert.Text = result.ToString();
}
I want to sum up my Amount column, but I receive this error message
Additional information: Index was outside the bounds of the array.
Here is the definition of the Balance table from SQL database:
CREATE TABLE [dbo].[Balance]
(
[BalanceID] [int] IDENTITY(1,1) NOT NULL,
[Sn] [nvarchar](50) NULL,
[Description] [nvarchar](1000) NULL,
[Date] [date] NULL,
[Amount] [decimal](8, 0) NULL
)
Here is the code C# that accesses the table via SQL inline
cn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select sum(Amount) from Balance where Sn=#sn and Date Between #SD and #ED";
cmd.Parameters.Add(new SqlParameter("#sn", txtSn.Text));
cmd.Parameters.Add(new SqlParameter("#SD", DTPStart.Text));
cmd.Parameters.Add(new SqlParameter("#ED", DTPEnd.Text));
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Debt = reader.GetDecimal(4);
}
reader.Close();
cn.Close();
Any help will be much appreciated!
Method GetDecimal gets the value of column having zero-based index provided as argument of method call.
You're returning only one column in your query Select sum(Amount) from Balance, but trying to achieve fifth column in reader.GetDecimal(4)
So change your code to
Debt = reader.GetDecimal(0);
Update: As it was noted in comments - in your particular case you don't need ExecuteReader at all. Since you're returning single value from server - you can use ExecuteScalar instead, which executes the query, and returns the first column of the first row in the result set returned by the query.
I'm trying to insert two data columns into my SQL Server database but I get an error at the code line -> cmd.ExecuteNonQuery();
Cannot insert the value NULL into column OrderID, table RestaurantApp.dbo.Junc_Order; column does not allow nulls. INSERT fails.
The OrderID column is actually the primary key in my data table. I set it identity(1, 1) and want to insert other data and meanwhile it can insert 1, 2, 3, 4....automatically.
Here is the part of my code:
string insertString = "INSERT INTO Junc_Order(ID, Quantity)values (#ID, #Quantity)";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.Parameters.AddWithValue("#ID", r_ID);
cmd.Parameters.AddWithValue("#Quantity", r_Quantity);
cmd.ExecuteNonQuery();
I already get connection with database ahead of these codes, so the problem should not be that.
Updated Junc_Order table design:
OrderID (PK,FK,int,not null)
ID(FK,int,not null)
Quantity(int,not null)
By viewing your question, it seems that your insert query is not correct:
First of all, you don't need to insert "OrderID" as it is primary key identity so sql server automatically insert it.
second, somewhere you are getting "r_ID" as null that's why you are facing error.Verify it and modify your code with the following:
string insertString = "INSERT INTO Junc_Order(Quantity) values(#Quantity)";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.Parameters.AddWithValue("#Quantity", r_Quantity);
cmd.ExecuteNonQuery();
In my table I have many rows with data.
One row has seven columns with values.
Is it possible to delete from one row values of two columns and rest five leave without changes?
Can I to it with SQL delete?
cmd.CommandText = #"DELETE ImageData,"
+ " ContentType, "
+ " FROM Users "
+ " WHERE UserName = #UserName";
cmd.Parameters.Add(new SqlParameter("#UserName", username));
cmd.Parameters.Add(new SqlParameter("#ImageData", ImageData));
cmd.Parameters.Add(new SqlParameter("#ContentType", ContentType));
In my code I can't delete like this, is it wrong?
Does anyone know how to delete them?
I assume it's not DELETE you need but UPDATE.
DELETE always removes an entire row.
UPDATE allows you to change individual columns in a row.
codefragment
#"UPDATE Users "
+ "SET ContentType = NULL, "
+ " ImageData = NULL "
+ "WHERE Username = #UserName";
You need to use an UPDATE statement for this. DELETE is only for deleting whole row(s) at a time.
You can't actually "delete" them as though it was cells in a spreadsheet though. Assuming the columns are nullable you can set them to NULL as below.
cmd.CommandText = #"UPDATE ImageData
SET ContentType = NULL, Users = NULL
WHERE UserName = #UserName";
cmd.Parameters.Add(new SqlParameter("#UserName", username));
you could update the row:
UPDATE Users
SET ImageData = NULL, ContentType = NULL
WHERE UserName = #UserName