Invalid column name while using C# for SQL Server - c#

This is my code in C#. I am just trying to add data to my table in the database. However, I have been having this issue for only ages. It says:
invalid column name.
Fotograf database is the only database I have and table ODEV1 is the only table I created. When I edit data through SQL Server there is not an issue, but when I try it by using Visual Studio C# I have issues.
Any help appreciated thank you!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace SQL_ORNEK2
{
class Program
{
static void Main(string[] args)
{
SqlConnection baglanti = new SqlConnection();
baglanti.ConnectionString = "Server=LAPTOP-K3JLTUR0; database=Fotograf; integrated security=True";
SqlCommand komut = new SqlCommand();
komut.Connection = baglanti;
string name;
name = Console.ReadLine().ToString();
string surname;
surname = Console.ReadLine().ToString();
int age;
age = Convert.ToInt32(Console.ReadLine());
string job;
job = Console.ReadLine().ToString();
komut.CommandText = "INSERT INTO dbo.ODEV1 VALUES('name', 'surname', age, 'job')";
baglanti.Open();
int sonuc = komut.ExecuteNonQuery();
Console.WriteLine(sonuc);
Console.ReadKey();
baglanti.Close();
}
}
}

Your insert statement is incorrect. You're using the list of columns in place of the values to insert. It should look something like this:
insert into dbo.ODEV1 (name, surname, age, job) values ('Harold', 'Green', 25, 'nerd')
To insert the actual data from the variables you read from user input, you'll want to use SQL parameters:
komut.Parameters.AddWithValue("#name", name);
komut.Parameters.AddWithValue("#surname", surname);
komut.Parameters.AddWithValue("#age", age);
komut.Parameters.AddWithValue("#job", job);
komut.CommandText = "insert into dbo.ODEV1 (name, surname, age, job) values (#name, #surname, #age, #job)";

If you use SSMS (SQL-Server Management Studio which is free) to create your INSERT INTO statement by right clicking the desired table, select "script table as", select "INSERT To" to a new query window we get this (using a table named Customers).
INSERT INTO [dbo].[Customer]
([FirstName]
,[LastName]
,[Address]
,[City]
,[State]
,[ZipCode]
,[AccountNumber]
,[JoinDate])
VALUES
(<FirstName, nvarchar(max),>
,<LastName, nvarchar(max),>
,<Address, nvarchar(max),>
,<City, nvarchar(max),>
,<State, nvarchar(max),>
,<ZipCode, nvarchar(max),>
,<AccountNumber, nvarchar(max),>
,<JoinDate, datetime2(7),>)
Now change the VALUES section by using a DECLARE for each value.
DECLARE #FirstName nvarchar(max)
DECLARE #LastName nvarchar(max)
DECLARE #Address nvarchar(max)
DECLARE #City nvarchar(max)
DECLARE #State nvarchar(max)
DECLARE #ZipCode nvarchar(max)
INSERT INTO Customer (FirstName,LastName,[Address],City,[State],ZipCode) VALUES (#FirstName,#LastName,#Address,#City,#State,#ZipCode)
Next, create a class rather than placing data operations into Program.cs with a method specific to adding a new record (the following still uses Customers table).
Full source where the following code comes from.
An alternate to cmd.Parameters.AddWithValue is cmd.Parameters.Add which provides fine tuning the type of the parameter.
The alternate to getting the new primary key if needed is to add a semi-colon to the end of the INSERT INTO and adding SELECT CAST(scope_identity() AS int); then use Convert.ToInt32(cmd.ExecuteScalar()) to get the new key.
So after testing with SSMS simply paste the query into a string variable and if this does not work there is something else going on.
public bool AddCustomer(string FirstName, string LastName, string Address, string City, string State, string ZipCode, ref int NewPrimaryKeyValue)
{
bool success = false;
using (var cn = new SqlConnection { ConnectionString = ConnectionString })
{
using (var cmd = new SqlCommand { Connection = cn })
{
cmd.CommandText =
"INSERT INTO Customer (FirstName,LastName,[Address],City,[State],ZipCode) " +
"VALUES (#FirstName,#LastName,#Address,#City,#State,#ZipCode)";
try
{
cmd.Parameters.AddWithValue("#FirstName", FirstName);
cmd.Parameters.AddWithValue("#LastName", LastName);
cmd.Parameters.AddWithValue("#Address", Address);
cmd.Parameters.AddWithValue("#City", City);
cmd.Parameters.AddWithValue("#State", State);
cmd.Parameters.AddWithValue("#ZipCode", ZipCode);
cn.Open();
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
cmd.CommandText = "Select ##Identity";
NewPrimaryKeyValue = Convert.ToInt32(cmd.ExecuteScalar());
success = true;
}
}
catch (Exception ex)
{
HasErrors = true;
ExceptionMessage = ex.Message;
NewPrimaryKeyValue = -1;
success = false;
}
}
}
return success;
}
Calling the above method.
You can also validate column names using the following (still keeping with Customer table)
SELECT ORDINAL_POSITION,
COLUMN_NAME,
DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customer'
AND TABLE_SCHEMA = 'dbo';
Results
1,id,int
2,FirstName,nvarchar
3,LastName,nvarchar
4,Address,nvarchar
5,City,nvarchar
6,State,nvarchar
7,ZipCode,nvarchar
8,AccountNumber,nvarchar
9,JoinDate,datetime2
Edit
Another option is to create a class which represents data to be inserted e.g.
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string AccountNumber { get; set; }
public DateTime? JoinDate { get; set; }
}
Then here we use the values passed. Note, in this version cmd.Parameters.AddWithValue is replaced with cmd.Parameters.Add and the query to get the new primary key is appended after the INSERT INTO separated by a semi-colon.
To call create an instance of the Customer class, populate properties and call the method.
public bool AddCustomer(Customer customer)
{
bool success = false;
using (var cn = new SqlConnection { ConnectionString = ConnectionString })
{
using (var cmd = new SqlCommand { Connection = cn })
{
cmd.CommandText =
"INSERT INTO Customer (FirstName,LastName,[Address],City,[State],ZipCode) " + // insert
"VALUES (#FirstName,#LastName,#Address,#City,#State,#ZipCode);" + // insert
"SELECT CAST(scope_identity() AS int);"; // get new primary key
try
{
cmd.Parameters.Add(new SqlParameter("#FirstName", SqlDbType.NVarChar))
.Value = customer.FirstName;
cmd.Parameters.Add(new SqlParameter("#LastName", SqlDbType.NVarChar))
.Value = customer.LastName;
cmd.Parameters.Add(new SqlParameter("#Address", SqlDbType.NVarChar))
.Value = customer.Address;
cmd.Parameters.Add(new SqlParameter("#City", SqlDbType.NVarChar))
.Value = customer.City;
cmd.Parameters.Add(new SqlParameter("#State", SqlDbType.NVarChar))
.Value = customer.State;
cmd.Parameters.Add(new SqlParameter("#ZipCode", SqlDbType.NVarChar))
.Value = customer.ZipCode;
cn.Open();
customer.Id = Convert.ToInt32(cmd.ExecuteScalar());
success = true;
}
catch (Exception ex)
{
HasErrors = true;
ExceptionMessage = ex.Message;
customer.Id = -1;
success = false;
}
}
}
return success;
}

Related

C# - System Data SqlClient SqlException

So I am in the midst of debugging a program I have been working on quite sometime that will email the user an email that will the user an email that contains information on an error a client is having trying to get into a mobile app. The problem that I am having is even though I have set the parameter, I am getting the following error message:
The parameterized query '(#USER_NAME varchar(8000))SELECT USER_NAME, EMAIL, FIRST_NAME, L' expects the parameter '#USER_NAME', which was not supplied.
I have never encountered this error before so I am not sure if there is something I am missing in my code or if I just put in the wrong syntax. Below is both the method where the error is happening in and the class that this method uses:
Method:
private static MyHomeInformation GetUserDataFromMyHome(string username)
{
MyHomeInformation myHomeInformation = null;
using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.MyHomeConnectionString))
{
SqlCommand sqlError = connection.CreateCommand();
sqlError.CommandText = #"SELECT USER_NAME, EMAIL, FIRST_NAME, LAST_NAME, TRAVELER_UID FROM TANDT_PORTAL.dbo.[USER] WHERE USER_NAME = #USER_NAME";
sqlError.Parameters.Add("#USER_NAME", System.Data.SqlDbType.VarChar);
connection.Open();
SqlDataReader reader = sqlError.ExecuteReader();
if (reader.Read())
{
myHomeInformation = new MyHomeInformation();
myHomeInformation.myHomeUserName = Utilities.FromDBValue<string>(reader["USER_NAME"]);
myHomeInformation.myHomeEmail = Utilities.FromDBValue<string>(reader["EMAIL"]);
myHomeInformation.myHomeFirstName = Utilities.FromDBValue<string>(reader["FIRST_NAME"]);
myHomeInformation.myHomeLastName = Utilities.FromDBValue<string>(reader["LAST_NAME"]);
myHomeInformation.myHomeTravelerUID = Utilities.FromDBValue<Guid>(reader["TRAVELER_UID"]);
}
}
return myHomeInformation;
}
Class:
class MyHomeInformation
{
public string myHomeUserName { get; set; }
public string myHomeEmail { get; set; }
public string myHomeFirstName { get; set; }
public string myHomeLastName { get; set; }
public Guid myHomeTravelerUID { get; set; }
}
Change the sqlError.Parameters.Add to AddWithValue
private static MyHomeInformation GetUserDataFromMyHome(string username)
{
MyHomeInformation myHomeInformation = null;
using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.MyHomeConnectionString))
{
SqlCommand sqlError = connection.CreateCommand();
sqlError.CommandText = #"SELECT USER_NAME, EMAIL, FIRST_NAME, LAST_NAME, TRAVELER_UID FROM TANDT_PORTAL.dbo.[USER] WHERE USER_NAME = #USER_NAME";
sqlError.Parameters.AddWithValue("#USER_NAME", username); // THIS ROW SHOULD BE UPDATED
connection.Open();
SqlDataReader reader = sqlError.ExecuteReader();
if (reader.Read())
{
myHomeInformation = new MyHomeInformation();
myHomeInformation.myHomeUserName = Utilities.FromDBValue<string>(reader["USER_NAME"]);
myHomeInformation.myHomeEmail = Utilities.FromDBValue<string>(reader["EMAIL"]);
myHomeInformation.myHomeFirstName = Utilities.FromDBValue<string>(reader["FIRST_NAME"]);
myHomeInformation.myHomeLastName = Utilities.FromDBValue<string>(reader["LAST_NAME"]);
myHomeInformation.myHomeTravelerUID = Utilities.FromDBValue<Guid>(reader["TRAVELER_UID"]);
}
}
return myHomeInformation;
}
Here is an example of the correct way to use the parameters collection add function:
SqlParameter param = new SqlParameter("#USER_NAME", SqlDbType.NVarChar, 8000);
param.Value = "Sam";
sqlError.Parameters.Add(param);
Note the setting of the value to Sam.
You could also use the function AddWithValue if you don't want to create the param variable. (However, #JoelCoehoorn will be worried about performance issues - see question comments)
You add your parameter to the call, but give the parameter no value.
change
sqlError.Parameters.Add("#USER_NAME", System.Data.SqlDbType.VarChar);
to
sqlError.Parameters.Add("#USER_NAME", System.Data.SqlDbType.VarChar).value = username;

Cannot add or update a child row: a foreign key constraint fails - stops at 1 insertion

What I'm trying to do is that, once I insert the data, it won't insert the same user TWICE due to having multiple trials. However, I'm getting the above error. My insert statement for inserting into user is
bool userisExist = checkUser(personName, age, gender, handedness, comments);
if (!userisExist)
{
MySqlCommand insertUser = new MySqlCommand();
insertUser.Connection = c;
insertUser.CommandText = "INSERT INTO user (userID, name, age, gender, handedness, comments) VALUES(NULL, #personName , #age , #gender , #handedness , #comments)";
insertUser.Parameters.Add("#personName", MySqlDbType.VarChar).Value = personName;
insertUser.Parameters.Add("#age", MySqlDbType.Int64).Value = age;
insertUser.Parameters.Add("#gender", MySqlDbType.VarChar).Value = gender;
insertUser.Parameters.Add("#handedness", MySqlDbType.VarChar).Value = handedness;
insertUser.Parameters.Add("#comments", MySqlDbType.VarChar).Value = comments;
insertUser.ExecuteNonQuery();
Console.WriteLine("User Data has been inserted.");
}
else
{
Console.WriteLine("User Data already exist.");
}
And my insert statement for gazeperiod is
insertGazePeriod.Connection = c;
insertGazePeriod.CommandText = "INSERT INTO gazeperiod (gazeID, duration, userID) VALUES(NULL, #duration , LAST_INSERT_ID())";
insertGazePeriod.Parameters.Add("#duration", MySqlDbType.Int64).Value = duration;
insertGazePeriod.ExecuteNonQuery();
Console.WriteLine("Gaze Period data has been inserted.");
//END INSERT gazeperiod
}
And my checkUser is
private bool checkUser(String personName, String age, String gender, String handedness, String comments)
{
try
{
int returnValue = -1;
MySqlCommand selectUser = new MySqlCommand();
selectUser.Connection = c;
selectUser.CommandText = "SELECT userID from user WHERE name= #personName AND age = #age AND gender = #gender AND handedness = #handedness AND comments = #comments";
selectUser.CommandType = CommandType.Text;
selectUser.Parameters.Add("#personName", MySqlDbType.VarChar).Value = personName;
selectUser.Parameters.Add("#age", MySqlDbType.Int64).Value = age;
selectUser.Parameters.Add("#gender", MySqlDbType.VarChar).Value = gender;
selectUser.Parameters.Add("#handedness", MySqlDbType.VarChar).Value = handedness;
selectUser.Parameters.Add("#comments", MySqlDbType.VarChar).Value = comments;
returnValue = (int)selectUser.ExecuteScalar();
Console.WriteLine("returnValue-" +returnValue);
return true;
}
catch (Exception e)
{
Console.WriteLine("returnValue Exception-" + e.ToString());
return false;
}
}
Right now, it's only printing the first user, and stops to print the other data as there is already a user with the current ID. I don't want multiple insertions of the same user.
I think the problem is in your INSERT sql statement:
insertUser.CommandText = "INSERT INTO user (userID, name, age, gender, handedness, comments) VALUES(NULL, #personName , #age , #gender , #handedness , #comments)";
I'm pretty sure you do not want to insert NULL in the userID column. If it is an AUTO_INCREMENT column, you should leave that behind.

Returning multiple variables from SQL query

My table structure is as follows:
Session
--------------
SessionID (PK)
RoomID
SessionDate
SessionTimeStart
SessionTimeEnd
I have a following query which will always return one row and display in DGV. I use DataAdapter for connection:
DataTable queryResult = new DataTable();
string ConnStr = "Data Source=DUZY;Initial Catalog=AutoRegSQL;Integrated Security=True";
SqlConnection MyConn = new SqlConnection(ConnStr);
MyConn.Open();
//SQL query that returns todays sessions for the given roomID
string query = #"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = #RoomID " +
" AND SessionDate = cast(getdate() as date) ";
SqlCommand command = new SqlCommand(query, MyConn);
command.Parameters.Add("RoomID", SqlDbType.Char).Value = RoomID;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(queryResult);
I would like to save the query result into multiple strings representing table columns, i.e.
SessionIDstring = query result for SessionID column
RoomIDstring = query result for RoomID column
and so on...
Is it possible to achieve it using one query, or do I have to create 5 queries for each column?
Something similar to this, perhaps, using ADO.NET?
//SQL query that returns todays sessions for the given roomID
string query = #"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = #RoomID " +
" AND SessionDate = cast(getdate() as date) ";
using (var connection = new SqlConnection(ConnStr))
using (var command = new SqlCommand(query, connection))
{
command.Parameters.Add("RoomID", SqlDbType.Char).Value = RoomID;
try
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
// Note that reader[x] has the equivalent type to the type
// of the returned column, converted using
// http://msdn.microsoft.com/en-us/library/cc716729.aspx
// .ToString() if the item isn't null is always ok
string SessionIDstring = reader[0].ToString(); // it should be an int
// reading it twice is ok
int RoomID = (int)reader[1]; // it should be an int
string RoomIDstring = reader[1].ToString(); // it should be an int
if (reader.Read())
{
throw new Exception("Too many rows");
}
}
else
{
throw new Exception("No rows");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
This code was adapted from MSDN ADO.NET Code Examples. I added some usings and made it single row. I don't even want to know why MSDN examples don't go the full length with using.
Note that SqlDataAdapter are built to recover multiple rows/big data and put them in a DataSet. You can use them for single row data, but it's much easier to simply use a SqlDataReader if you only want to fill some variables.
declare #col1 int
declare #col2 varchar(42)
select #col1 = col1
, #col2 = col2
, ....
You could create a class like so...
public class SessionDto
{
public string SessionID {get; set;}
public string RoomID {get; set;}
public string SessionDate {get; set;}
public string SessionTimeStart {get; set;}
public string SessionTimeEnd {get; set;}
}
And then have a method that takes a Room ID and builds your session object
public SessionDto GetSessionData(int roomId)
{
using (var cnn = new SqlConnection(ConnStr))
{
SessionDto sessionDto;
string query = #"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = #RoomID " +
" AND SessionDate = cast(getdate() as date) ";
cnn.Open();
using (var cmd = new SqlCommand(query,cnn))
{
cmd.Parameters.Add("#RoomID", SqlDbType.Char).Value = roomId;
using (var rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
while (rdr.Read())
{
sessionDto = new sessionDto{
SessionID = rdr.GetString(0),
RoomID = rdr.GetString(1),
SessionDate = rdr.GetString(2),
SessionTimeStart = rdr.GetString(3),
SessionTimeEnd = rdr.GetString(4)
};
}
}
}
}
}
return sessionDto;
}
A lot of this is hand typed as I havent got access to VS right now,
but you should get it to work.
Also, I have used rdr.GetString(), there are other methods for GetType().

Cannot insert the data into the table using C# visual studio 2008

hello every i was trying to create simple student form n add the data to the database but coudlnt do this, there was no error during the execution of the program, application executes nicely but no changes in the table, n the values are nt inserted into the table, what might b the problem plz suggest me, im writing my code below..
thanq in advance :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace School.Project
{
class Student
{
public static string constr = System.Configuration.ConfigurationManager.ConnectionStrings"SchoolConnectionString"].ConnectionString;
public static int AddStudent(string title, string fname, string lname, string fathername, string gender, string clas, string sec, int age, string dob, string religion, string caste, string image, string address, string homeno, string cell, string email)
{
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlTransaction t = con.BeginTransaction();
SqlCommand cmd = new SqlCommand("INSERT INTO Student (Title,FirstName,LastName,FatherName,Gender,Class,Section,Age,DateOfBirth,Religion,Caste,Image,Address,HomePhone,CellPhone,Email) VALUES(#Title,#FirstName,#LastName,#FatherName,#Gender,#Class,#Section,#Age,#DateOFBirth,#Religion,#Caste,#Image,#Address,#HomePhone,#CellPhone,#Email)",con);
cmd.Parameters.AddWithValue("#Title", title);
cmd.Parameters.AddWithValue("FirstName", fname);
cmd.Parameters.AddWithValue("LastName", lname);
cmd.Parameters.AddWithValue("#FatherName", fathername);
cmd.Parameters.AddWithValue("#Gender", gender);
cmd.Parameters.AddWithValue("#Class", clas);
cmd.Parameters.AddWithValue("#Section", sec);
cmd.Parameters.AddWithValue("Age", age);
cmd.Parameters.AddWithValue("DateOfBirth", dob);
cmd.Parameters.AddWithValue("#Religion", religion);
cmd.Parameters.AddWithValue("Caste", caste);
cmd.Parameters.AddWithValue("Image", image);
cmd.Parameters.AddWithValue("Address", address);
cmd.Parameters.AddWithValue("#HomePhone", homeno);
cmd.Parameters.AddWithValue("#CellPhone", cell);
cmd.Parameters.AddWithValue("#Email", email);
cmd.Transaction = t;
int i = cmd.ExecuteNonQuery();
t.Commit();
con.Close();
return i;
}
private void btSave_Click(object sender, EventArgs e)
{
string title = cbTitle.SelectedItem.ToString();
string fname = txtfname.Text;
string lname = txtlname.Text;
string fathername = txtfatherName.Text;
string gender = cbGender.SelectedItem.ToString();
string clas = cbClass.SelectedItem.ToString();
string section = cbSection.SelectedItem.ToString();
int age = int.Parse(txtAge.Text);
string dob = txtdob.Text;
string religion = txtReligion.Text;
string caste = txtCaste.Text;
string imagepath = txtpath.Text;
string address = txtAddress.Text;
string homeno = txtHome.Text;
string cell = txtCell.Text;
string email = txtEMail.Text;
int i = Project.Student.AddStudent(title, fname, lname, fathername, gender, clas, section, age, dob, religion, caste, imagepath, address, homeno, cell, email);
if (i == 1)
{
MessageBox.Show("Student Added Succesfully, Thanq", "Inserted", MessageBoxButtons.OK, MessageBoxIcon.Information);
ClearAll();
}
else
{
MessageBox.Show("Couldnt enter the data", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
add a bracket [ ] on some fields of your query because some of the are reserved words:
SqlCommand cmd = new SqlCommand("
INSERT INTO Student ([Title],FirstName,LastName,
FatherName,Gender,
[Class],Section,Age,DateOfBirth,
Religion,Caste,[Image],Address,
HomePhone,CellPhone,Email)
VALUES(#Title,#FirstName,#LastName,
#FatherName,#Gender,#Class,#Section,
#Age,#DateOFBirth,#Religion,#Caste,
#Image,#Address,#HomePhone,
#CellPhone,#Email)",con);
[Title]
[Image]
UPDATED 1
Instead of SqlTransaction t = con.BeginTransaction();
try this:
SqlTransaction t = con.BeginTransaction(IsolationLevel.ReadCommitted)
Source: Use database transactions
Some of your parameters contain the "#" symbol and some don't....
1.) don't pass so many parameters. You want to add a STUDENT, that should ring all your bells. Pass only one parameter - class Student populated with the values you want.
2.) I don't think a transaction is necessary here. You want to push only one object, so if it fails, the result is the same - no changes done.
3.) as Daren said, you don't have properly written parameters in your query
EDIT:
Just tried the simplified version and it works like a charm... Here's the code:
Page.aspx.cs
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
btn.Click += new EventHandler(btn_Click);
}
void btn_Click(object sender, EventArgs e)
{
Student student = new Student() { Id = 1, Name = "John" };
int rowsAffected = Student.AddStudent(student);
Response.Write(rowsAffected);
}
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public static int AddStudent(Student s)
{
string conString = System.Configuration.ConfigurationManager.ConnectionStrings["string1"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Students (Name) VALUES (#Name)", con);
cmd.Parameters.AddWithValue("#Name", s.Name);
return cmd.ExecuteNonQuery();
}
}
}
Please, try to modify it to suit your needs and let me know, if it finally works. It has some problems (like not putting the class Student in a separate file), but I hope you get the idea.

oledb retrieve entire record and return from .accdb

example of a return function that returns only string value, how do I return multiple values consisting of different data types in a single record by simply calling one function?
public static string selectPassword(string user)
{
using (var connection = new OleDbConnection(connectionString))
using (var command = connection.CreateCommand())
{
command.Parameters.AddWithValue("#user", user);
command.CommandText = "SELECT [Password] FROM [Password_Table] WHERE Password_ID = [#user]";
command.CommandType = CommandType.Text;
connection.Open();
var value = command.ExecuteScalar();
return value == DBNull.Value ? null : value.ToString();
}
}
my record would be searched by Participant_Name, and would need to return Participant_Name, Participant_ID, Address, Contact_Number & Gender fields, all consisting of string, integers etc..
Create a data-type which consists of fields and properties that are able to hold the information that you want to retrieve.
Populate an instance of that type in your method, and return it.
Something like this, for instance:
public class Participant
{
public int Id { get; private set; }
public string Name {get; set;}
public string Address {get; set; }
public Participant( int id, string name, string address )
{
this.Id = id;
this.Name = name;
this.Address = address;
}
}
public Participant GetParticipant( string name )
{
using( var conn = new OleDbConnection (connectionString) )
{
using( var cmd = connection.CreateCommand() )
{
command.CommandText = "SELECT [Id], [Name], [Address] FROM Participant WHERE [name] LIKE #p_name";
command.Parameters.Add ("#p_name", OleDbType.VarChar).Value = name + "%";
using( var reader = command.ExecuteReader() )
{
if( !reader.HasRows() ) return null;
reader.Read();
return new Participant (reader.GetString("Id"), reader.GetString("name"), reader.GetString("address"));
}
}
}
}
Note: there can be syntax errors, since I haven't pulled it through the compiler, but I think you'll catch the drift.
for your needs you should return a DataRow object or an object array which you can get by calling .ItemArray on a DataRow
what you need to change in your method above is to use a DataAdapter and call its Fill method to fill a DataTable then return the first row of such DataTable, if any row is present.
you could also do this with the DataReader but then you should construct the array or objects container to return by yourself... I think dataRow.ItemArray is faster to code.

Categories

Resources