I'm trying to print a table from my database but I want to filter it using this block code, what I want to do is print the data between two hours but I don't know is the input format of the hour is correct, so here's the code:
string horaI=null;
string horaF=null;
string[] hr1 = null;
string[] hr2 = null;
on load....
dateTimePicker1.CustomFormat = "HH:mm tt"; // Only use hours and minutes
horaI = dateTimePicker1.Value.ToString("HH:mm tt");
hr1 = horaI.Split();
string connectionstring = null;
string sql = null;
string data = null;
connectionstring = "server=127.0.0.1; database=gimnasio5; uid=root; pwd=0000000000;";
sql = "SELECT IdMembresia, Nombre, Apellido, Tipo, Fecha_Inicio,
Fecha_Vencimiento, Inscripcion, Total,Impreso_Corte FROM membresia where
Impreso_Corte='No impreso' or (Fecha_Membresia between #d1 and #d2 and
Hora_Membresia between #d3 and #d4) order by gimnasio5.membresia.IdMembresia;";
var dtable = new DataTable("membresia");
var conn = new MySql.Data.MySqlClient.MySqlConnection(connectionstring);
var cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
var dscmd = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
using (conn)
{
var param = new MySql.Data.MySqlClient.MySqlParameter("#d1", MySql.Data.MySqlClient.MySqlDbType.Date);
param.Direction = ParameterDirection.Input;
param.Value = DateTime.Today;
cmd.Parameters.Add(param);
param = new MySql.Data.MySqlClient.MySqlParameter("#d2", MySql.Data.MySqlClient.MySqlDbType.Date);
param.Direction = ParameterDirection.Input;
param.Value = DateTime.Today;
cmd.Parameters.Add(param);
//The error can be here because when I use it with dates only it works fine
//but when I add this part of code, fails.
param = new MySql.Data.MySqlClient.MySqlParameter("#d3", MySql.Data.MySqlClient.MySqlDbType.Time);
param.Direction = ParameterDirection.Input;
param.Value = hr1[0]; //Convert.ToDateTime(hr1[0]).ToString("HH:mm");
cmd.Parameters.Add(param);
param = new MySql.Data.MySqlClient.MySqlParameter("#d4", MySql.Data.MySqlClient.MySqlDbType.Time);
param.Direction = ParameterDirection.Input;
param.Value = hr2[0]; //Convert.ToDateTime(hr2[0]).ToString("HH:mm");
cmd.Parameters.Add(param);
conn.Open();
dscmd.Fill(dtable);
}
But Im geting and error: An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
Additional information: Fatal error encountered during command execution.
I get the error when I try to fill the MySqlAdapter Object:
dscmd.Fill(dtable);
I thought it was the format I input the time, but as you can see in the code I use to forms for it, but neither of both works, and returns the same error code.
My column in the MySQL database is set to save time type, so the problem isn't in the table.
The hour in the database is saved like this, the column is time type:
12:03:00
21:34:00
Thanks in advanced.
Table structure
CREATE TABLE `membresia` (
`IdMembresia` int(11) NOT NULL AUTO_INCREMENT,
`Nombre` varchar(100) NOT NULL,
`Apellido` varchar(100) NOT NULL,
`Tipo` varchar(100) NOT NULL,
`Fecha_Inicio` date NOT NULL,
`Fecha_Vencimiento` date NOT NULL,
`Inscripcion` varchar(20) DEFAULT NULL,
`Estado_membresia` varchar(15) NOT NULL,
`Fecha_modificacion` date NOT NULL,
`Total` decimal(10,2) NOT NULL,
`Nota` varchar(200) DEFAULT NULL,
`Fecha_Membresia` date NOT NULL,
`Impreso_Corte` varchar(20) NOT NULL,
`IdSocio` int(11) DEFAULT NULL,
`Hora_Membresia` time NOT NULL,
PRIMARY KEY (`IdMembresia`),
KEY `L_Id2` (`IdSocio`),
KEY `F_Nombre` (`Nombre`),
KEY `F_Apelli` (`Apellido`),
CONSTRAINT `F_Apelli` FOREIGN KEY (`Apellido`) REFERENCES `socios` (`Apellido`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `F_Nombre` FOREIGN KEY (`Nombre`) REFERENCES `socios` (`Nombre`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `L_Id2` FOREIGN KEY (`IdSocio`) REFERENCES `socios` (`IdSocio`) ON DELETE CASCADE ON UPDATE CASCADE)
ENGINE=InnoDB DEFAULT CHARSET=utf8;
Code like this way:
SqlConnection conn = new SqlConnection("server=127.0.0.1; database=gimnasio5; uid=root; pwd=0000000000;");
conn.Open();
string query = string.Format(#"SELECT IdMembresia, Nombre, Apellido, Tipo, Fecha_Inicio,
Fecha_Vencimiento, Inscripcion, Total, Impreso_Corte FROM membresia where
Impreso_Corte = 'No impreso' or(Fecha_Membresia between '{0}' and '{1}' and
Hora_Membresia between '{2}' and '{3}') order by gimnasio5.membresia.IdMembresia", dateTimePicker1.Value.ToShortDateString(), dateTimePicker2.Value.ToShortDateString(), dateTimePicker3.Value.ToString("hh:mm:ss"), dateTimePicker4.Value.ToString("hh:mm:ss"));
SqlCommand cmd = new SqlCommand(query, conn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
conn.Close();
return dt;
Related
I am learning mvc from this video where I am getting data from a form and saving it to database. When I ran my code first it gave an error stating
Procedure or function 'spAddEmployee' expects parameter '#Employee_Name', which was not supplied.
I followed a solution in which I initialized my stored procedure as NULL but now I am getting another error stating "#Parameter1 is not a parameter for procedure".
This is my stored procedure
ALTER PROCEDURE [dbo].[spAddEmployee]
(
#Employee_Name varchar(max) = NULL,
#Employee_Age int = NULL,
#Employee_Salary int = NULL,
#Employee_City varchar(50) = NULL
)
AS
BEGIN
INSERT INTO tblEmployee (Employee_Name, Employee_Age, Employee_Salary, Employee_City)
VALUES (#Employee_Name, #Employee_Age, #Employee_Salary, #Employee_City)
END
And this is my ADO.NET code:
public void AddEmployee(Employee employee)
{
string connectionString = ConfigurationManager.ConnectionStrings["EmployeeContext"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spAddEmployee", con)
{
CommandType = CommandType.StoredProcedure
};
SqlParameter paramName = new SqlParameter();
paramName.ParameterName = "#Employee_Name";
paramName.Value = employee.Employee_Name;
cmd.Parameters.Add(paramName);
SqlParameter paramAge = new SqlParameter();
paramAge.ParameterName = "#Employee_Age";
paramAge.Value = employee.Employee_Age;
cmd.Parameters.Add(paramAge);
SqlParameter paramSalary = new SqlParameter();
paramSalary.ParameterName = "#Employee_Salary";
paramSalary.Value = employee.Employee_Salary;
cmd.Parameters.Add(paramSalary);
SqlParameter paramCity = new SqlParameter();
paramCity.ParameterName = "#Employee_City";
paramCity.Value = employee.Employee_City;
cmd.Parameters.Add(paramCity);
con.Open();
cmd.ExecuteNonQuery();
}
}
And this is my controller code
[HttpPost]
[ActionName("Create")]
public ActionResult Create_Post(FormCollection formCollection)
{
Employee employee = new Employee();
employee.Employee_Name = formCollection["Employee_Name"];
employee.Employee_Age = Convert.ToInt32(formCollection["Employee_Age"]);
employee.Employee_Salary = Convert.ToInt32(formCollection["Employee_Salary"]);
employee.Employee_City = formCollection["Employee_City"];
EmployeeBuissnessLayer employeeBuissnessLayer = new EmployeeBuissnessLayer();
employeeBuissnessLayer.AddEmployee(employee);
return RedirectToAction("Index");
}
I am getting error at line
employeeBuissnessLayer.AddEmployee(employee);
Please help I have tried a lot of solutions but none of them have worked.
This
SqlParameter paramName = new SqlParameter();
paramName.ParameterName = "#Employee_Name";
paramName.Value = employee.Employee_Name;
cmd.Parameters.Add(paramName);
Should be
SqlParameter paramName = new SqlParameter();
paramName.ParameterName = "#Employee_Name";
// Always set the datatype
paramName.SqlDbType = SqlDbType.NVarChar;
// For strings, always set the length
paramName.Size = 128; // Max string length
// Ensure you pass DBNull not C# null
paramName.Value = employee.Employee_Name ?? System.DBNull.Value;
cmd.Parameters.Add(paramName);
Note: its best practice not to name your Stored Procedure with the sp prefix.
I have to add 4 values into my table:#SNTeacher,#name,#pwd and #courseID.The #courseID is a FK in my RegisterTeacher table and a PK I Courses table along with another attribute-#coursename.
My problem is that when I want to insert the values into the table, I get an error at #courseID saying that it can't convert from varchar to int although my #courseID is an int.
My #courseID and #coursename are binded to comboBoxcourse1 and it has DisplayMember-coursename and ValueMember=courseID.My opinion is that it makes the confusion between the two of them since #coursename is a varchar, but then again I don't see the logic since I'm adding the #courseID parameter to the table RegisterTeacher.
I also tried to parse it in 3 different ways that I have also found here, on Stack Overflow but still I get errors saying that the input string was not in a correct format.
This is my code with the error and in is also the last method I used to try to parse the value:
private void btnRegister_Click(object sender, EventArgs e)
{
string connString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\source\repos\VIAUniversityCollegeAttendanceApp\VIAUniversityCollegeAttendanceApp\DatabaseAttendanceStudents.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand("Insert into RegisterTeacher values(#SNTeacher,#name,#pwd,#courseID) ", con);
cmd.Parameters.AddWithValue("#SNTeacher", textBoxSN.Text);
cmd.Parameters.AddWithValue("#name",textBoxName.Text);
cmd.Parameters.AddWithValue("#pwd", textBoxpwd.Text);
string nvarchar = "#courseID";
var one = int.Parse(nvarchar);
var bone = int.TryParse(nvarchar, out one);
cmd.Parameters.AddWithValue("#courseID", comboBoxcourse1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Registration succesfull!");
}
This should work for you:
int parameterValue;
SqlParameter parameter = new SqlParameter("#courseID", SqlDbType.Int);
if(Int32.TryParse(comboBoxcourse1.SelectedValue?.ToString() ?? String.Empty, out parameterValue))
{
parameter.Value = parameterValue;
}
else
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
I am trying to insert data into a SQL Server table, but it is not allowing me to do so and throws an error. I think the error is from the role I don't know how to fix it; please I need your help - thank you.
This is the member table that I am using:
CREATE TABLE [dbo].[Member]
(
[Member_Username] NVARCHAR (50) NOT NULL,
[Password] NVARCHAR (25) NOT NULL,
[Role] NVARCHAR (10) NULL,
[FirstName] NVARCHAR (50) NOT NULL,
[LastName] NVARCHAR (50) NOT NULL,
[Gender] NVARCHAR (8) NOT NULL,
[Email] NVARCHAR (50) NULL,
[DateOfBirth] DATE NOT NULL,
PRIMARY KEY CLUSTERED ([Member_Username] ASC)
);
And this is the error I get when inserting the values into the table:
System.Data.SqlClient.SqlException:
The parameterized query '(#memberU nvarchar(1), #pwd nvarchar(1), #role nvarchar(4000), #fna' expects the parameter '#role', which was not supplied.
This is the member class that I have for inserting the user in the database table:
public void AddMember()
{
// Open database connection
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Config.GetConnectionStr();
conn.Open();
// Prepare SQL command with parameters
string sql = "INSERT INTO Member VALUES (#memberU, #pwd, #role, #fname, #lname, #gender, #email, #dob)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("memberU", this.Member_Username);
cmd.Parameters.AddWithValue("pwd", this.Password);
cmd.Parameters.AddWithValue("role", this.Role);
cmd.Parameters.AddWithValue("fname", this.FirstName);
cmd.Parameters.AddWithValue("lname", this.LastName);
cmd.Parameters.AddWithValue("email", this.Email);
// handling null values for gender and date of birth column
if (this.Gender != null)
{
cmd.Parameters.AddWithValue("gender", this.Gender);
}
else
{
cmd.Parameters.AddWithValue("gender", DBNull.Value);
}
if (this.DateofBirth != null)
{
cmd.Parameters.AddWithValue("dob", this.DateofBirth);
}
else
{
cmd.Parameters.AddWithValue("dob", DBNull.Value);
}
// Execute command
cmd.ExecuteNonQuery();
}
And this is the sign up button:
protected void btnSignUp_Click(object sender, EventArgs e)
{
if (Page.IsValid)// assuming you have done validations using validation controls
{// c create a new object of type member and set all it's properties to values from controls
Members user = new Members();
//reading required values
user.FirstName = txtFirstName.Text;
user.LastName = txtLastName.Text;
user.Member_Username = txtUserName.Text;
user.Password = txtPassword.Text;
user.Email = txtEmail.Text;
user.Gender = rdoGender.SelectedValue;
//reading values that allow null in the database (date of birth)
if (string.IsNullOrEmpty(txtDOB.Text))
{
user.DateofBirth = null;
}
else
{
user.DateofBirth = DateTime.Parse(txtDOB.Text);
}
//call the addMember method
user.AddMember();
//redirect the user to homePage
Response.Redirect("Login.aspx");
}
}
can you try when you add parameters like ( cmd.parameters.addwithvalue("#role",value).
I have a table:
CREATE TABLE [dbo].[DeliveryData](
[DeliveryId] [int] IDENTITY(1,1) NOT NULL,
...
CONSTRAINT [PK_DeliveryData] PRIMARY KEY CLUSTERED
(
[DeliveryId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
And code:
public void GetPrimaryKeyColumns(SqlConnection conn) {
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "select * from [dbo].[DeliveryData]";
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly);
DataTable schema = reader.GetSchemaTable();
DataColumn[] columns = schema.PrimaryKey;
...
}
cmd, reader, and schema all look good, but columns ends up a zero length array. Shouldn't it contain "DeliveryId"? How can I get the primary column "DeliveryId"?
Thanks for the help!
Blake
MSSQL doesn't return correct primary key information in all cases using GetSchemaTable. (Not too surprising. For example, almost all DB vendors support ODBC better than MS.) The following query, however, does work:
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE as kcu
ON kcu.CONSTRAINT_CATALOG = tc.CONSTRAINT_CATALOG
AND kcu.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
AND kcu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
AND kcu.TABLE_CATALOG = tc.TABLE_CATALOG
AND kcu.TABLE_SCHEMA = tc.TABLE_SCHEMA
AND kcu.TABLE_NAME = tc.TABLE_NAME
WHERE tc.CONSTRAINT_TYPE ='PRIMARY KEY'
AND tc.TABLE_SCHEMA = 'dbo'
AND tc.TABLE_NAME = 'DeliveryData'
ORDER BY ORDINAL_POSITION;
The schema table is not the DeliveryData table. You must inspect the schema table where the IsKey column is true and then grab the ColumnName field. You can then use that find the real column on a regular data table.
Update
GetSchemaTable() returns a data table of metadata information which you can see in the documentation: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getschematable(v=vs.110).aspx
You end up with as many rows in the returned DataTable as you would have columns in the query if you were to run the query. Here is a partial screenshot of the schema table I get from a test table in my database. Notice every column is now a row, and the IsKey field will tell you if the column is a key column:
If you want to use the PrimaryKey property on a DataTable do not use GetSchemaTable(), just use a SqlDataAdapter to fill a regular DataTable.
Update 2
use CommandBehavior.KeyInfo instead of CommandBehavior.SchemaOnly
Using SMO
using Microsoft.SqlServer.Management.Smo;
....
Server svr = new Server("Your Server Name");
Database db = svr.Databases["Your Database Name"];
Table tbl = db.Tables["DeliveryData"];
foreach (Column c in tbl.Columns)
{
bool isAKeyColumn = c.InPrimaryKey
}
This is a complete solution:
public List<string> GetPrimaryKeyColumns(DbConnection conn, string schema, string table) {
DbCommand cmd = conn.CreateCommand();
DbParameter p = cmd.CreateParameter();
p.ParameterName = "#schema";
p.Value = schema;
p.DbType = DbType.String;
p.Direction = ParameterDirection.Input;
cmd.Parameters.Add(p);
p = cmd.CreateParameter();
p.ParameterName = "#table";
p.Value = table;
p.DbType = DbType.String;
p.Direction = ParameterDirection.Input;
cmd.Parameters.Add(p);
cmd.CommandText = #"SELECT kcu.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE as kcu
ON kcu.CONSTRAINT_CATALOG = tc.CONSTRAINT_CATALOG
AND kcu.CONSTRAINT_SCHEMA = tc.CONSTRAINT_SCHEMA
AND kcu.CONSTRAINT_NAME = tc.CONSTRAINT_NAME
-- AND kcu.TABLE_CATALOG = tc.TABLE_CATALOG doesn't work on MySQL
AND kcu.TABLE_SCHEMA = tc.TABLE_SCHEMA
AND kcu.TABLE_NAME = tc.TABLE_NAME
WHERE tc.CONSTRAINT_TYPE ='PRIMARY KEY'
AND tc.TABLE_SCHEMA = #schema
AND tc.TABLE_NAME = #table
ORDER BY ORDINAL_POSITION";
DbDataReader reader = cmd.ExecuteReader(CommandBehavior.KeyInfo);
List<string> res = new List<string>();
while (reader.Read()) {
var str = reader[0];
if (str != System.DBNull.Value)
res.Add((string) str);
}
reader.Dispose();
cmd.Dispose();
return res;
}
This answer to this question is fine, but I'm looking for ADO.NET code to be able to send an array or table to an Oracle procedure and then use that table in the procedure.
In SQL Server table-valued parameters, it's pretty straightforward:
CREATE TYPE [dbo].[IntTable] AS TABLE(
[intvalue] [int] NOT NULL,
PRIMARY KEY CLUSTERED
(
[intvalue] ASC
)WITH (IGNORE_DUP_KEY = OFF)
)
GO
CREATE PROCEDURE dbo.UseTable
#SomeInt INT
,#IntTable dbo.IntTable READONLY
AS
BEGIN
-- Do whatever using #SomeInt and #IntTable like:
INSERT INTO Assignments (masterid, childid)
SELECT #SomeInt, intvalue
FROM #IntTable
END
GO
Then on the client:
var param = new List<int>();
param.Add(1);
param.Add(2);
Cm.Parameters
.AddWithValue("#IntTable", param /* IEnumerable<Int> */)
.SqlDbType = SqlDbType.Structured
This is what I currently have:
CREATE OR REPLACE TYPE TRAIT_ID_TABLE AS TABLE OF NUMBER;
PROCEDURE SET_TRAITS(P_CUST_TANK_PROD_ID IN CUST_TANK_PROD.CUST_TANK_PROD_ID%TYPE, P_TRAIT_IDS IN TRAIT_ID_TABLE)
AS
BEGIN
DELETE FROM TANK_TRAIT
WHERE CUST_TANK_PROD_ID = P_CUST_TANK_PROD_ID;
INSERT INTO TANK_TRAIT(CUST_TANK_PROD_ID, TRAIT_ID)
SELECT P_CUST_TANK_PROD_ID, COLUMN_VALUE FROM TABLE(P_TRAIT_IDS);
COMMIT;
EXCEPTION
WHEN OTHERS
THEN
ROLLBACK;
END;
var param = new OracleParameter();
param.ParameterName = "P_TRAIT_IDS";
param.OracleDbType = OracleDbType.Decimal;
param.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
param.Direction = ParameterDirection.Input;
param.Value = traitIdList.ToArray<int>();
param.Size = traitIdList.Count;
cmd.Parameters.Add(param);
And I get this on the ExecuteNonQuery:
System.AccessViolationException was caught
Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Source=Oracle.DataAccess
StackTrace:
at Oracle.DataAccess.Client.OpsSql.ExecuteNonQuery(IntPtr opsConCtx, IntPtr& opsErrCtx, IntPtr& opsSqlCtx, IntPtr& opsDacCtx, IntPtr opsSubscrCtx, Int32& isSubscrRegistered, OpoSqlValCtx*& pOpoSqlValCtx, OpoSqlRefCtx& pOpoSqlRefCtx, IntPtr[] pOpoPrmValCtx, OpoPrmRefCtx[] pOpoPrmRefCtx, OpoMetValCtx*& pOpoMetValCtx, Int32 prmCnt)
at Oracle.DataAccess.Client.OracleCommand.ExecuteNonQuery()
at EDC2.Domain.TraitList.SaveTraits(String connectionString) in C:\code\EDC2\trunk\app\EDC2.Domain\Trait.cs:line 195
InnerException:
This works for ODP.NET (odac):
Your Oracle package will be setup like:
CREATE OR REPLACE package SOME_PACKAGE as
...
type t_number_tab is table of number index by pls_integer;
...
procedure ins_test(i_id_tab in t_number_tab, o_inserted out number);
end SOME_PACKAGE;
CREATE OR REPLACE package body SOME_PACKAGE as
procedure ins_test(i_id_tab in t_number_tab, o_inserted out number) is
begin
-- inserts all records to test table based on incoming table of ids
forall i in i_id_tab.first .. i_id_tab.last
insert into TEST_TAB
(id, val1, val2)
select id,val1,val2
from main_tab
where id = i_id_tab(i);
o_inserted := SQL%ROWCOUNT;
commit;
exception
when others then
rollback;
raise;
end ins_test;
...
end SOME_PACKAGE;
Then your C# code would look like:
string connStr = "User Id=xxx;Password=xxxx;Data Source=xxxxx;";
OracleConnection _conn = new OracleConnection(connStr);
_conn.Open();
OracleCommand cmd = _conn.CreateCommand();
cmd.CommandText = "some_package.ins_test";
cmd.CommandType = CommandType.StoredProcedure;
OracleParameter p1 = new OracleParameter();
OracleParameter p2 = new OracleParameter();
p1.OracleDbType = OracleDbType.Decimal;
p1.Direction = ParameterDirection.Input;
p2.OracleDbType = OracleDbType.Decimal;
p2.Direction = ParameterDirection.Output;
p1.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
p1.Value = new int[3] { 1, 2, 3 };
p1.Size = 3;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.ExecuteNonQuery();