Inserting data using Linq - linq-to-sql

I have a linq query to insert data in table. but its not working. I saw some example on internet tried to do like that but doesn't seems to work.
Tablename: login has 3 columns userid, username and password. I set userid as autoincrementing in database. So I have to insert only username and password everytime.Here's my code.
linq_testDataContext db = new linq_testDataContext();
login insert = new login();
insert.username = userNameString;
insert.Password = pwdString;
db.logins.Attach(insert);// tried to use Add but my intellisence is not showing me Add.I saw attach but dosent seems to work.
db.SubmitChanges();

have a look on http://www.codeproject.com/KB/linq/LINQToSQLBaseCRUDClass.aspx
linq_testDataContext db = new linq_testDataContext();
login insert = new login();
insert.username = userNameString;
insert.Password = pwdString;
db.logins. InsertOnSubmit(insert);
db.SubmitChanges();
If you Attach - It should attach to the particular object Context .But it wont reflect in database .If you want to insert any values try with InsertOnSubmit(object) and do
SubmitChanges() to save it in database

Attach() is the wrong method, you need to call InsertOnSubmit() to let Linq-To-Sql generate an insert statement for you. Attach() is for distributed scenarios, where your entity has not been retrieved via the same data-context that is used for submitting changes.
linq_testDataContext db = new linq_testDataContext();
login insert = new login();
insert.username = userNameString;
insert.Password = pwdString;
db.logins.InsertOnSubmit(insert);// tried to use Add but my intellisence is not showing me Add.I saw attach but dosent seems to work.
db.SubmitChanges();

Method to save employee details into Database.
Insert, Update & Delete in LINQ C#
Employee objEmp = new Employee();
// fields to be insert
objEmp.EmployeeName = "John";
objEmp.EmployeeAge = 21;
objEmp.EmployeeDesc = "Designer";
objEmp.EmployeeAddress = "Northampton";
objDataContext.Employees.InsertOnSubmit(objEmp);
// executes the commands to implement the changes to the database
objDataContext.SubmitChanges();

Related

Trying to update a column in database but NOT NULL attributes are not letting me update the values. I am using Laravel

I am trying to update the column with some other data but database table is not letting me update the table because of the NOT NULL constraints in it. I have this option of setting all the fields to NULL but I dont think that will be a good practice. Please I need a solution to it if anyone can help. I get the following error
Illuminate \ Database \ QueryException (HY000)
SQLSTATE[HY000]: General error: 1364 Field 'first_name' doesn't have a default value (SQL: insert into users (subject_id, updated_at, created_at) values (?, 2019-07-30 13:46:42, 2019-07-30 13:46:42))
Previous exceptions
SQLSTATE[HY000]: General error: 1364 Field 'first_name' doesn't have a default value (HY000)`
I have tried setting all the values to NULL and it worked but I want to work with some fields setting as NOT NULL and update the ones which are NULL and also if we can fetch or set the fields automatically to what we have ?
This is my controller where I am trying to update the field if this is required or help you understand my problem
public function deleteSubject($id) {
echo $id;
// die();
if(Auth::check()) {
$findSubject = Auth::user()->where('subject_id', $id);
$users = new User();
$users->subject_id = null;
$users->save();
// echo($findSubject);
// die();
Session::flash("message", "You subject has been deleted. You can add a new Subject now.");
return redirect('/subjects');
} else {
Session::flash("message", "Please sign in to access this page");
return redirect('/signup');
}
}
The following should work for your code. As it was said in the previous comment, it's because you try to create a new instance of a user without inserting value.
It look like you are trying to delete the subject associate with the authenticated user, so I suppose that you don't really need to create a new user, instead I think you should dissociate the user and the subject. So, the following should work for your code.
The purpose of that variant is to take the authenticated user and put a null value for the subject_id.
public function deleteSubject($id) {
echo $id;
// die();
if(Auth::check()) {
$user = User::where('subject_id', $id)->first(); // This will get the user that have the subect_id, but it's assuming that only one user have this subject_id.
// You can also do this just uncomment the first line below and comment the other one above.
// $user = User::find(Auth::user->id);
$user->subject_id = null;
$user->save()
Session::flash("message", "You subject has been deleted. You can add a new Subject now.");
return redirect('/subjects');
} else {
Session::flash("message", "Please sign in to access this page");
return redirect('/signup');
}
}
I think that you should take a look about how MVC work.
https://selftaughtcoders.com/from-idea-to-launch/lesson-17/laravel-5-mvc-application-in-10-minutes/
You should also take a look at relationship in Laravel: https://laravel.com/docs/5.8/eloquent-relationships
MVC and Eloquent-Relationships will help you understand some function in laravel to achieve this kind of goal really quickly.
If you get a User model and a Subject model, you can simply do something like this:
$user = User->find(Auth::user()->id);
$user->subjects()->dissociate($id);
I'm not sure, but I think the Auth facade let you use the user model function, so maybe this could work to:
Auth::user()->subjects()->dissociate($id);
You should also take a look at middleware: https://laravel.com/docs/5.8/middleware
With middleware, you can put rules like the one you are using to send a message to the user saying that he/she need to be log in to access the page into the middleware and reusing it whenever you need.

Laravel 5.3 Trigger

is there a way to make a laravel trigger for this sql command? sorry I am new to laravel and having a hard time figuring it out.
So what should happen is when the table.a get its content, it will automactically fill the column with ids from the other table. is it possible for laravel? Thank you so much.
UPDATE table_a
INNER JOIN table.b ON table_a.account_code =
table.ac_code
SET table_a.ut_id = table.ut_id, table_a.pj_id
= table.pj_id
I used to use laravel event for trigger stuff in laravel (it assumes you have models on this). In your to be listened Model_B (table_b), you can define something like :
public function boot()
{
parent::boot();
static::created(function ($model) {
/*update table a here*/
$ut_id = $model->ut_id;
$pj_id = $model->pj_id;
Table_A::customUpdate($ut_id, $pj_id);
});
}
Please define your public customUpdate( ) as you want.
Check laravel doc above to see other possibilities for boot methods: creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored

Change sha1 password mysql and Cakephp log in

I'm very new to CakePHP.
I've recently taken over a project that was built in CakePHP v 1.2.4.8284.
I'm trying to change the password for the login page.
There is only one user stored in a mysql database.
fields - id, username, password(varchar 40), nacl(char(6), firstname, lastname
In phpAdmin, I've tried changing the password while using the SHA1 function, but that doesn't work.
I've even tried creating a new user, but the new user information will not work either.
I've narrowed it down to the usercontroller in the following if statement:
if ($results && $results['User']['password'] == sha1($results['User']['nacl'] . sha1($this->data['User']['password'])))
It looks like the password in the database should have sha1(nacl field) + sha1(password field).
But it is all wrapped in a sha1.
I'm not sure how the encryption is working.
Any help would be appreciated.
Thanks in advance.
Here is the complete login function.
function login()
{
$this->set('error', false);
if ($this->Session->read('user'))
{
$this->redirect('/test-folder/');
} else {
$this->User->set($this->data);
if ($this->data) {
//$results = $this->User->findByUsername($this->data['User']['username']);
$results = $this->User->find('first', array(
'conditions' => array('username' => $this->data['User']['username'])
));
if ($results && $results['User']['password'] == sha1($results['User']['nacl'] . sha1($this->data['User']['password']))) {
$this->Session->write('user', $this->data['User']['username']);
$this->Session->write('admin', $results['User']['group']);
$this->redirect('/test-folder/');
} else {
$this->set('error', true);
}
}
}
}
Get the Security.salt in Config/core.php: 'securitysaltvalue'
Take a password 'yourplainpassword'
UPDATE user SET password = SHA1( CONCAT('securitysaltvalue', 'yourplainpassword')) WHERE id = 123
According to your code, you should be able to generate a new Password with these steps:
1) Generate a Password, for example "test123"
2) Get the id of the user you want to change the password for, for example 123
3) Execute this SQL in your phpMyAdmin (Replace my demo values!!!)
UPDATE user SET password = CONCAT( SHA1(nacl), SHA1("test123")) WHERE id = 123
And please make a complete DB dump on that table before any changes. And better yet, test on some development instance.
The answer from #StefanoDP works, but the table name is 'users', not 'user'. So the command should be:
UPDATE users SET password=SHA1(CONCAT('securitysaltvalue','yourplainpassword')) WHERE id=123;
Don't forget to add the semicolon at the end of the statement.

how can i use hibernate to loging in a jsp page

im using hibernate with my jsp page and mySQL , i know just how to save a session like that :
<%Session hibernateSession = MyDB.HibernateUtil.currentSession(); Transaction tx = hibernateSession.beginTransaction();
Student std = new Student();
std.setUserName("David");
hibernateSession.save(std);%>
, but how can i selecte from a table and print it like in mysql select * from student wher userName = *** and how can i update ?
finaly can i use hibernate in Login ?
Refer this for complete HQL help: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html

LINQ To SQL does not work when adding new object

I use the following code to insert a new record to my Users table:
public bool CreateUser(User obj)
{
obj.Id = Guid.NewGuid();
using (_db = new CMSDataContext())
{
obj.SiteId = SiteID;
_db.Users.InsertOnSubmit(obj);
_db.SubmitChanges();
}
return true;
}
I do not get any errors, and everything seems fine. I can read a record from database with same DataContext. But after the above method runs completely, I see nothing new in my Users table. Why?
Is the id column truly a PK in the sql server database?