ExecuteNonQuery Violation of Primary Key after putting value? - c#

I'm trying to write a CRUD app and I have a problem with the Create method. Program is crashing with error
System.Data.SqlClient.SqlException: 'Violation of PRIMARY KEY constraint 'PK_Pracownicy'. Cannot insert duplicate key in object 'dbo.Pracownicy'. The duplicate key value is (11).
The statement has been terminated.'
But I can see in my SQL Server that this position is added to Pracownicy table, so I don't know where is a problem. Its look like the error is generated after I put new values to table
class SqlHelper
{
public int RowsLenght { get; set; }
private SqlConnection sqlConnection;
public string Command { get; set; }
public SqlHelper(string connectionString)
{
sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
}
public int Create(string command, SqlParameter []parameters)
{
//wykonanie polecenia na bazie
using var cmd = new SqlCommand(command, sqlConnection);
cmd.Parameters.AddRange(parameters);
ShowTable(cmd);
return cmd.ExecuteNonQuery();
}
public int Read(string command)
{
//wykonanie polecenia na bazie
using var cmd = new SqlCommand(command, sqlConnection);
ShowTable(cmd);
return cmd.ExecuteNonQuery();
}
private int ShowTable(SqlCommand command)
{
var reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetInt32(0) + "\t" + reader.GetString(2) + " " +
reader.GetString(1) + "\t" + reader.GetString(3));
RowsLenght++;
}
reader.Close();
return RowsLenght;
}
}
class Program
{
static void Main()
{
SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder
{
DataSource = #"HAL\MSSERVER",
InitialCatalog = "ZNorthwind",
IntegratedSecurity = true,
ConnectTimeout = 30,
Encrypt = false,
TrustServerCertificate = false,
ApplicationIntent = 0,
MultiSubnetFailover = false
};
var connectionS = connectionString.ConnectionString;
SqlHelper sql = new SqlHelper(connectionS);
var command = "SELECT * FROM dbo.Pracownicy";
sql.Read(command);
command = "INSERT INTO dbo.Pracownicy (IDpracownika, Nazwisko, Imię, Stanowisko) VALUES (#IDpracownika, #Nazwisko, #Imie, #Stanowisko)";
var parameters = SetUpParameters(sql.RowsLenght);
sql.Create(command, parameters);
}
private static SqlParameter[] SetUpParameters(int lenght)
{
//inicjalizacja zmiennych:
Console.WriteLine("Podaj imie nowego pracownika: ");
var fname = Console.ReadLine();
Console.WriteLine("Podaj nazwisko pracownika: ");
var lname = Console.ReadLine();
Console.WriteLine("Podaj stanowisko pracownika: ");
var position = Console.ReadLine();
SqlParameter []param = new SqlParameter[4];
param[0] = new SqlParameter("IDpracownika", lenght + 1);
param[1] = new SqlParameter("Imie", fname);
param[2] = new SqlParameter("Nazwisko", lname);
param[3] = new SqlParameter("Stanowisko", position);
return param;
}
}
Thanks

Related

C# bool array index was outside the bounds of the array on declaration and initialization

I have this function, which updates some info in my database. It works properly until bool[] days = new bool[7]; and it throws exception message - 'index is outside the bounds of the array'. I cannot understand how it is out of bounds, when I just declared and initialized it.
public static void UpdateDepartment(Department department, string oldName)
{
if (department!=null)
{
try
{
using (MySqlConnection conn = new MySqlConnection(ConnectionString))
{
string query = "select * from people where department = #oldName";
List<User> results = new List<User>();
MySqlCommand cmd_refactor = new MySqlCommand(query, conn);
cmd_refactor.Parameters.AddWithValue("#oldName", oldName);
conn.Open();
MySqlDataReader dataReader = cmd_refactor.ExecuteReader();
while (dataReader.Read())
{
int id = int.Parse(dataReader[0].ToString());
string username = dataReader[1].ToString();
string firstName = dataReader[2].ToString();
string lastName = dataReader[3].ToString();
string email = dataReader[4].ToString();
string phoneNumber = dataReader[5].ToString();
PersonPosition position =
(PersonPosition)Enum.Parse(typeof(PersonPosition), dataReader[6].ToString(), true);
double salary = Double.Parse(dataReader[7].ToString());
Department departmentResult = new Department(dataReader[8].ToString());
ShiftType shiftType =
(ShiftType)Enum.Parse(typeof(ShiftType), dataReader[11].ToString(), true);
bool[] days = new bool[7];
for (int i = 0; i < 7; i++)
{
days[i] = bool.Parse(dataReader[i + 12].ToString());
}
User user = new User(username, firstName, lastName, email, position, salary, shiftType,
days, departmentResult, id, phoneNumber);
results.Add(user);
}
conn.Close();
foreach (var item in results)
{
conn.Open();
item.UserDepartment = department;
UpdateUser(item);
conn.Close();
}
query = "update departments set departmentName = #name where departmentName = #oldName";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("#name", department.Name);
cmd.Parameters.AddWithValue("#oldName", oldName);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
throw new NoConnectionException();
}
}
}
days[i] can't be out of range. It must be the other array in this line which throws this error: dataReader[i + 12]

Convert string to date in gridview that connected to mysql

how to convert the string to date in grid view that connected to Mysql via object data source.
for CoopF_From and CoopF_To columns.
Convert.ToDateTime "shows the the date and the time, and I want only to show the date"
the code in data access layer
namespace Demo.CoopF
{
public class CoopF
{
public string CoopF_FName { get; set; }
public string CoopF_MName { get; set; }
public string CoopF_LName { get; set; }
public int CoopF_ID { get; set; }
public string CoopF_Mobile { get; set; }
public string CoopF_Email { get; set; }
public string CoopF_From { get; set; }
public string CoopF_To { get; set; }
}
public class CoopFDataAccessLayer
{
public static void UpdateCoop( int CoopF_ID, string CoopF_FName, string CoopF_MName, string CoopF_LName, string CoopF_Mobile, string CoopF_Email, string CoopF_From, string CoopF_To)
{
string CF = "server=localhost; userid=; password=; database=; allowuservariables=True";
using (MySqlConnection connection = new MySqlConnection(CF))
{
string UpdateQuery = " Update coop_female SET CoopF_FName=#CoopF_FName," + " CoopF_MName=#CoopF_MName," + " CoopF_LName=#CoopF_LName," + "CoopF_Mobile=#CoopF_Mobile," + "CoopF_Email=#CoopF_Email,"+ "CoopF_From=#CoopF_From,"+"CoopF_To=#CoopF_To=#CoopF_To WHERE CoopF_ID=#CoopF_ID";
MySqlCommand cmd = new MySqlCommand(UpdateQuery, connection);
cmd.Connection.Open();
MySqlParameter paramCoopF_FName = new MySqlParameter("#CoopF_FName", CoopF_FName);
cmd.Parameters.Add(paramCoopF_FName);
MySqlParameter paramCoopF_MName = new MySqlParameter("#CoopF_MName", CoopF_MName);
cmd.Parameters.Add(paramCoopF_MName);
MySqlParameter paramCoopF_LName = new MySqlParameter("#CoopF_LName", CoopF_LName);
cmd.Parameters.Add(paramCoopF_LName);
MySqlParameter paramCoopF_ID = new MySqlParameter("#CoopF_ID", CoopF_ID);
cmd.Parameters.Add(paramCoopF_ID);
MySqlParameter paramCoopF_Mobile = new MySqlParameter("#CoopF_Mobile", CoopF_Mobile);
cmd.Parameters.Add(paramCoopF_Mobile);
MySqlParameter paramCoopF_Email = new MySqlParameter("#CoopF_Email", CoopF_Email);
cmd.Parameters.Add(paramCoopF_Email);
MySqlParameter paramCoopF_From = new MySqlParameter("#CoopF_From", Convert.ToDateTime(CoopF_From));
cmd.Parameters.Add(paramCoopF_From);
MySqlParameter paramCoopF_To = new MySqlParameter("#CoopF_To", Convert.ToDateTime(CoopF_To));
cmd.Parameters.Add(paramCoopF_To);
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
public static List<CoopF> GetAllEmployees()
{
List<CoopF> listCoopF = new List<CoopF>();
string CF = "server=localhost; userid=; password=; database=; allowuservariables=True";
using (MySqlConnection connection = new MySqlConnection(CF))
{
MySqlCommand cmd = new MySqlCommand("Select * from coop_female", connection);
connection.Open();
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
CoopF coop = new CoopF();
coop.CoopF_FName = rdr["CoopF_FName"].ToString();
coop.CoopF_MName = rdr["CoopF_MName"].ToString();
coop.CoopF_LName = rdr["CoopF_LName"].ToString();
coop.CoopF_ID = Convert.ToInt32(rdr["CoopF_ID"]);
coop.CoopF_Mobile = rdr["CoopF_Mobile"].ToString();
coop.CoopF_Email = rdr["CoopF_Email"].ToString();
coop.CoopF_From = rdr["CoopF_From"].ToString();
coop.CoopF_To= rdr["CoopF_To"].ToString();
listCoopF.Add(coop);
}
}
return listCoopF;
}
public static void DeleteCoop(int CoopF_ID)
{
string CF = "server=localhost; userid=; password=; database=; allowuservariables=True";
using (MySqlConnection connection = new MySqlConnection(CF))
{
string UpdateQuery = " Delete from Coop_female WHERE CoopF_ID=#CoopF_ID";
MySqlCommand cmd = new MySqlCommand(UpdateQuery, connection);
MySqlParameter param = new MySqlParameter("#CoopF_ID", CoopF_ID);
cmd.Parameters.Add(param);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
public static void InsertCoop(string CoopF_FName, string CoopF_MName, string CoopF_LName, int CoopF_ID, string CoopF_Mobile, string CoopF_Email, string CoopF_From, string CoopF_To)
{
string CF = "server=localhost; userid=; password=; database=; allowuservariables=True";
using (MySqlConnection connection = new MySqlConnection(CF))
{
string UpdateQuery = " INSERT INTO Coop_female (CoopF_FName, CoopF_Mname, CoopF_LName, CoopF_ID, CoopF_Mobile, CoopF_Email, CoopF_From, CoopF_To)" + " VALUES (#CoopF_FName,#CoopF_MName,#CoopF_LName,#CoopF_ID,#CoopF_Mobile,#CoopF_Email,#CoopF_From,#CoopF_To)";
MySqlCommand cmd = new MySqlCommand(UpdateQuery, connection);
MySqlParameter paramCoopF_FName = new MySqlParameter("#CoopF_FName", CoopF_FName);
cmd.Parameters.Add(paramCoopF_FName);
MySqlParameter paramCoopF_MName = new MySqlParameter("#CoopF_MName", CoopF_MName);
cmd.Parameters.Add(paramCoopF_MName);
MySqlParameter paramCoopF_LName = new MySqlParameter("#CoopF_LName", CoopF_LName);
cmd.Parameters.Add(paramCoopF_LName);
MySqlParameter paramCoopF_ID = new MySqlParameter("#CoopF_ID", CoopF_ID);
cmd.Parameters.Add(paramCoopF_ID);
MySqlParameter paramCoopF_Mobile = new MySqlParameter("#CoopF_Mobile", CoopF_Mobile);
cmd.Parameters.Add(paramCoopF_Mobile);
MySqlParameter paramCoopF_Email = new MySqlParameter("#CoopF_Email", CoopF_Email);
cmd.Parameters.Add(paramCoopF_Email);
MySqlParameter paramCoopF_From = new MySqlParameter("#CoopF_From", Convert.ToDateTime(CoopF_From));
cmd.Parameters.Add(paramCoopF_From);
MySqlParameter paramCoopF_To = new MySqlParameter("#CoopF_To", Convert.ToDateTime(CoopF_To));
cmd.Parameters.Add(paramCoopF_To);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}
}
in code behind
protected void lbInsert_Click(object sender, EventArgs e)
{
ObjectDataSource1.InsertParameters["CoopF_FName"].DefaultValue=((TextBox)GridView1.FooterRow.FindControl("TxtFName")).Text;
ObjectDataSource1.InsertParameters["CoopF_MName"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtMName")).Text;
ObjectDataSource1.InsertParameters["CoopF_LName"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtLName")).Text;
ObjectDataSource1.InsertParameters["CoopF_ID"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtID")).Text;
ObjectDataSource1.InsertParameters["CoopF_Mobile"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtMobile")).Text;
ObjectDataSource1.InsertParameters["CoopF_Email"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtEmail")).Text;
ObjectDataSource1.InsertParameters["CoopF_From"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtFrom")).Text;
ObjectDataSource1.InsertParameters["CoopF_To"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtTo")).Text;
ObjectDataSource1.Insert();
}
You can use following :
Convert.ToDateTime(CoopF_From).Date;
It will give you the Date value only
As I see it, you need to represent DateTime values as strings containing only the date part. There is a standard format specifier for this, namely "d".
The following interactive C# session illustrates the difference between ToString() and ToString("d").
> DateTime.Now.ToString()
"2017-01-07 18:13:00"
> DateTime.Now.ToString("d")
"2017-01-07"
More info

Update SQL comand doesn't change the data

I know may be it is stupid question. But This query doesn't work. I search solution more than 1 hour.
Please Help
public static bool ChangeEventStatus(Connector cn, EventData eventData)
{
int updatedRows = 0;
using (OleDbCommand cmd = cn.CreateCommand())
{
cmd.CommandText = "Update EventList Set IsProcessed = ? Where EventId = ?";
cmd.Parameters.Add("IsProcessed", OleDbType.Boolean).Value = true;
cmd.Parameters.Add("EventId", OleDbType.BigInt).Value = eventData.EventId;
updatedRows = cmd.ExecuteNonQuery();
}
return (updatedRows == 1);
}
What is wrong in my code. ChangeEventStatus method return true, but database records doesn't change.
public static bool ChangeEventStatus(Connector cn, EventData eventData)
{
int updatedRows = 0;
using (OleDbConnection conn = new OleDbConnection(someConnectionString));
{
conn.Open();
using (OleDbCommand cmd = cn.CreateCommand())
{
cmd.CommandText = "Update EventList Set IsProcessed = ? Where EventId = ?";
cmd.Parameters.Add("#IsProcessed", OleDbType.Boolean).Value = true;
cmd.Parameters.Add("#EventId", OleDbType.BigInt).Value = eventData.EventId;
updatedRows = cmd.ExecuteNonQuery();
}
return (updatedRows == 1);
}
}
I found problem. thanks everyone. I forgot commit transaction after updateting
I changed the code a bit and wrote the test. All work fine.
Check:
Connection string
Is you pass correct EventId to function ?
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Assert.AreEqual(true, ChangeEventStatus(new EventData() {EventId = 3}));
}
private static bool ChangeEventStatus(EventData eventData)
{
int updatedRows = 0;
using (var cn = new OleDbConnection("Provider=sqloledb;Data Source=localhost;Initial Catalog=FastExperiments;User Id = sa; Password = pass; "))
{
using (OleDbCommand cmd = cn.CreateCommand())
{
cn.Open();
cmd.CommandText = "Update EventList Set IsProcessed = ? Where EventId = ?";
cmd.Parameters.Add("IsProcessed", OleDbType.Boolean).Value = true;
cmd.Parameters.Add("EventId", OleDbType.BigInt).Value = eventData.EventId;
updatedRows = cmd.ExecuteNonQuery();
}
}
return (updatedRows == 1);
}
private class EventData
{
public int EventId { get; set; }
}
}

How can i call a Oracle connection method in C# with paramaters?

i have created a program in C# which inserts data into an Oracle database. It is pretty procedural though and i want to improve my program (and my knowledge) to use classes. I am having some trouble around calling a method with parameters. This is my code:
public class Oracle {
public void Insert() {
string oracleConnectionString = "User Id=" + l_orauser + "; Password=" + l_orapass + "; Data Source=" + l_oradb;
using (OracleConnection oracleConnection = new OracleConnection(oracleConnectionString)) {
oracleConnection.Open();
OracleGlobalization oracleSession = oracleConnection.GetSessionInfo();
oracleSession.DateFormat = "dd-mm-yyyy hh24:mi:ss";
oracleConnection.SetSessionInfo(oracleSession);
OracleTransaction oracleTransaction = oracleConnection.BeginTransaction();
OracleCommand oracleCommand = oracleConnection.CreateCommand();
oracleCommand.Transaction = oracleTransaction;
oracleCommand.CommandType = CommandType.Text;
string oracleCommandText = "insert into T1 (C1, C2, C3) values (:l_c1, :l_c2, :l_c3)";
oracleCommand.CommandText = oracleCommandText;
oracleCommand.BindByName = true;
oracleCommand.Parameters.Add("l_c1", OracleDbType.Byte, 3).Value = l_c1;
oracleCommand.Parameters.Add("l_c2", OracleDbType.Date).Value = l_c2;
oracleCommand.Parameters.Add("l_c3", OracleDbType.Varchar2, 1024).Value = l_c3;
try {
oracleCommand.ExecuteNonQuery();
oracleTransaction.Commit();
}
catch (Exception ex) {
oracleTransaction.Rollback();
MessageBox.Show(ex.Message);
}
finally {
oracleCommand.Parameters.Clear();
oracleCommand.Dispose();
oracleTransaction.Dispose();
oracleConnection.Close();
oracleConnection.Dispose();
}
}
}
}
I want to call this with some parameters - the variables: l_orauser, l_orapass, l_oradb, l_c1, l_c2, l_c3, which are taken from the elements of the form, for instance textbox, datetimepicker. How can i do that?
public static void Main(string[] args) {
var testOracle = new Oracle();
testOracle.Insert();
}
ok, so after discussing with Tim Freese i have decided to use constructors and an array of prameters.
For reference i have added the code, maybe somebody will find it useful:
public static void Main(string[] args) {
string oracleUser, oraclePassword, oracleDatabase;
List<string> oracleArguments = new List<string>();
//0 = oracleUser
//1 = oraclePassword
//2 = oracleDatabase
//3 = oracleCommandText
//4+ = oracleCommand.Parameters
l_orauser = "schema1";
l_orapass = "schema1pass";
l_oradb = "db1";
oracleArguments.Add(l_orauser);
oracleArguments.Add(l_orapass);
oracleArguments.Add(l_oradb);
Oracle testOracle = new Oracle();
testOracle.Insert(oracleArguments);
}
And the Oracle class:
public class Oracle {
public void Insert(List<string> oracleArguments) {
string oracleConnectionString = "User Id=" + oracleArguments[0] + "; Password=" + oracleArguments[1] + "; Data Source=" + oracleArguments[2];
using (OracleConnection oracleConnection = new OracleConnection(oracleConnectionString)) {
//do something
}
}
}

Json Deserialization

I want to use json to my android project. I am having some problem how to use json with .net. My code :
string stroutput = "";
try
{
string conStr = #"data source=.;database=Kelepir;Integrated Security=True;";
SqlConnection connection = new SqlConnection(conStr);
connection.Open();
string myquery = "select ProductID,ProductName,CategoryName,UnitPrice from Products";
SqlCommand cmd = new SqlCommand(myquery, connection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var nes = new
{
ProductID = reader["ProductID"].ToString(),
ProductName = reader["ProductName"].ToString(),
CategoryName = reader["CategoryName"].ToString(),
UnitPrice = reader["UnitPrice"].ToString()
};
stroutput = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(nes);
Response.Write(stroutput);
}
}
catch (Exception ex)
{
stroutput = "ERROR : " + ex.Message;
}
But my json has not this marks : ",", and "[ ]".
My output :
{"ProductID":"1","ProductName":"Şeker","CategoryName":"Tatlı","UnitPrice":"20"}
{"ProductID":"2","ProductName":"Kuruyemiş","CategoryName":"Tuzl","UnitPrice":"200"}
{"ProductID":"3","ProductName":"Baklagil","CategoryName":"Sebze","UnitPrice":"100"}
{"ProductID":"4","ProductName":"Bulgur","CategoryName":"Sebze","UnitPrice":"10"}
I want this format to my code :
{ "table_name":
[
{"ProductID":"1","ProductName":"Şeker","CategoryName":"Tatlı","UnitPrice":"20"}, {"ProductID":"2","ProductName":"Kuruyemiş","CategoryName":"Tuzl","UnitPrice":"200"},
{"ProductID":"3","ProductName":"Baklagil","CategoryName":"Sebze","UnitPrice":"100"},
{"ProductID":"4","ProductName":"Bulgur","CategoryName":"Sebze","UnitPrice":"10"}]
}
How I can do this ? Thanks...
give this a shot:
var rowList = new List<object>();
while (reader.Read())
{
var nes = new
{
ProductID = reader["ProductID"].ToString(),
ProductName = reader["ProductName"].ToString(),
CategoryName = reader["CategoryName"].ToString(),
UnitPrice = reader["UnitPrice"].ToString()
};
rowList.Add(nes);
}
var serializeMe = new {table_name = rowList }
stroutput = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(serializeMe );
Response.Write(stroutput);
You are serializing each row. What you want to do is pacakge each row into a colleciton and then serialize the collection as a whole.

Categories