I am trying to update one field in db which is of type Boolean. This is the table structure
usr_id int False
usr_fname nvarchar(50)
usr_lname nvarchar(50)
usr_username nvarchar(50)
usr_password nvarchar(MAX)
usr_email nvarchar(50)
usr_pwdresetstatus bit
This is something I am trying
public int ForGotPassword(string username, string emailid)
{
var result = db.tm_usr_usermaster.Where(m => m.usr_username == username && m.usr_email==emailid).Select(m => m.usr_isactive).SingleOrDefault();
bool isactive = Convert.ToBoolean(result);
if(isactive==false)
{
//Update query
}
else
{
}
I am receiving parameters username and email id if both matches pwdresetstatus should be updated as true. I can write sql equivalent here
Update tablename set pwdresetstatus=true where usr_username==username && usr_email==emailed. I have difficult times to go ahead
I tried this
tm_usr_usermaster users = db.tm_usr_usermaster.FirstOrDefault(x => x.usr_email==emailid && x.usr_username==username);
users.usr_pwdresetstatus = true;
db.SaveChanges();
and working fine. Thank you stephen
Related
I have the following function and table in my PostgreSQL database:
CREATE OR REPLACE FUNCTION generate_uid(size INT) RETURNS TEXT AS $$
DECLARE
characters TEXT := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
bytes BYTEA := gen_random_bytes(size);
l INT := length(characters);
i INT := 0;
output TEXT := '';
BEGIN
WHILE i < size LOOP
output := output || substr(characters, get_byte(bytes, i) % l + 1, 1);
i := i + 1;
END LOOP;
RETURN output;
END;
$$ LANGUAGE plpgsql VOLATILE;
create table users
(
userid text primary key default generate_uid(50)
, username varchar (50) not null
, pass varchar (50) not null
, firstname varchar (100) not null
, lastname varchar (100) not null
, email varchar (150) not null
, roleid int not null
, constraint fkrole foreign key(roleid) references userrole(roleid)
);
Then I call on the function in my DAO in JDBC with this block of code:
Account A = new Account();
String sha256hex = Hashing.sha256()
.hashString(password, StandardCharsets.UTF_8)
.toString();
try (Connection conn = CustomClassFactory.getConnection()) {
String sql = "INSERT INTO users (username, pass, firstname, lastname, email, roleid) VALUES (?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, userName);
ps.setString(2, sha256hex);
ps.setString(3, firstName);
ps.setString(4, lastName);
ps.setString(5, email);
ps.setInt(6, roleId);
System.out.println(ps.toString());
int i = ps.executeUpdate(); // <---update not query. this line is what sends the information to the DB
if (i == 0) {
System.out.println("Sorry, database was not updated. Returning to menu");
return null;
}
} catch (SQLException e) {
System.out.println("Sorry, database was not contacted. Bring your developer coffee. In the Insert Statement");
e.printStackTrace();
return null;
}
I am receiving the following error from the Stack Trace:
org.postgresql.util.PSQLException: ERROR: function gen_random_bytes(integer) does not exist
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Where: PL/pgSQL function generate_uid(integer) line 8 during statement block local variable initialization
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2552)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2284)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:322)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:481)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:401)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:164)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:130)
at dao.AccountDaoImp.CreateAccount(AccountDaoImp.java:35)
at testing.Tester.main(Tester.java:11)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "models.Account.toString()" because the return value of "dao.AccountDaoImp.CreateAccount(String, String, String, String, String, int)" is null
at testing.Tester.main(Tester.java:11)
How do I make sure it sees the function when I create a new user? The function is designed to generate a random string of text to use as a unique ID.
gen_random_bytes is part of the pgcrypto extension.
So run this in your database:
CREATE EXTENSION pgcrypto SCHEMA public;
To make sure you don't have to rely on search_path, you can prefix public to the function call, like in public.gen_random_uuid().
I have an Account table:
table Account
(
UserId int identity(1, 1),
UserName nvarchar(20) not null unique,
Password nvarchar(20) not null
)
By using LINQ. Whether I can check exist UserName for an account then. And it's true then get UserId for that account
(I'm use ASP MVC 4 with Entity Framework)
When using Linq to query from DB, I prefer to use query expression, that is closer to SQL notation than Lambda notation.
Given that you have the username:
try {
int userId = (from x in context.Account
where x.UserName == username
select x.UserId).SingleOrDefault());
if (userId > 0){
// user exists
}
else {
// user does not exist
}
}
catch(InvalidOperationException ex){
// has more than one element
}
var user = Context.Accounts.SinlgeOrDefault(user => user.UserName=="yourValue");
if(user!=null)
{
// you can safely access the user properties here
}
I have two tables:
create table dbo.Dates (
Id int not null
constraint Dates_Id_PK primary key clustered (Id),
[DateValue] date not null
}
create table dbo.Posts (
Id int identity not null
constraint Posts_Id_PK primary key clustered (Id),
Created datetime not null,
Title nvarchar (200) not null
)
For these tables I have Date and Post entities.
How can I get a table that has the column DateValue from Dates and the number of Posts with that date.
I need to match the datetime Created value to the date DateValue.
Thank you,
Miguel
I assume your Posts have dates with times, so you'll have to truncate them to the date part (as in the Date property of a DateTime):
from d in context.Dates
select new {
Date = d.DateValue,
NrOfPosts = (from p in context.Posts
where EntityFunctions.TruncateTime(t.Created) == d.DateValue
select p).Count()
}
you can use anonymous types. try the following snippet.
DateTime dateToMatch = GetDateToMatch();
using(YourEntities context = new YourEntities())
{
var result = context.Dates.Where(d => d.DateValue == dateToMatch)
.Select(d => new { Date = d.DateValue, PostCount = d.Posts.Count() });
}
Hope someone can help me out here as I'm a little stuck.
I'm building a service in front of a hiscore database for a game.
The database have the following two tables:
CREATE TABLE [dbo].[PB_HiscoreEntry] (
[Id] UNIQUEIDENTIFIER NOT NULL,
[PlayerId] UNIQUEIDENTIFIER NOT NULL,
[Score] INT NOT NULL,
[DateCreated] DATETIME NOT NULL
);
CREATE TABLE [dbo].[PB_Player] (
[Id] UNIQUEIDENTIFIER NOT NULL,
[UniquePlayerId] NCHAR (32) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[DateCreated] DATETIME NOT NULL
);
The idea is of course to only have each player once in the database and let them have multiple hiscore entries. This table PB_HiscoreEntry will have a lot of scores, but by doing a simple OrderBy descending, I can create a real hiscore list where the one with highest score is at the top and the lowest at the bottom.
My problem here is that my database don't have any idea of the actual Rank of the score compared to the others. This is something I should do as I do the OrderBy query described above.
Here is some code to help illutrate what I want to archive:
var q = (
from he in entities.PB_HiscoreEntry
orderby he.Score descending
select new HiscoreItem()
{
UserId = he.PB_Player.UniquePlayerId,
Username = he.PB_Player.Name,
Score = he.Score,
//Put in the rank, relative to the other entires here
Rank = 1
});
HiscoreItem, is just my own DTO i need to send over the wire.
So anybody have an idea of how I can do this or am I on a totally wrong path here?
You're on the right track, you just need to use the Queryable.Select overload that takes an extra index. Take a look at this:
var entries =
from entry in entities.PB_HiscoreEntry
orderby entry.Score descending
select entry;
// Note the (entry, index) lambda here.
var hiscores = entries.Select((entry, index) => new HiscoreItem()
{
UserId = entry.PB_Player.UniquePlayerId,
Username = entry.PB_Player.Name,
Score = entry.Score,
Rank = index + 1
});
I'm not 100% sure if Entity Framework knows how to work with the
Select<TSource, TResult>(this IQueryable<TSource>, Expression<Func<TSource, int, TResult>>) overload. If that's the case, just use the equivalent method of the static Enumerable class:
// Note the .AsEnumerable() here.
var hiscores = entries.AsEnumerable()
.Select((entry, index) => new HiscoreItem()
{
UserId = entry.PB_Player.UniquePlayerId,
Username = entry.PB_Player.Name,
Score = entry.Score,
Rank = index + 1
});
I hope this helps.
Is there a way to verify whether the table is exist inside the database in HTML5 local database?
I need to create 9 tables, and this method will run when the document ready. If each time the page start, it also calling the same method, will it not be waste of memory? I using it for the mobile device (iPhone).
This is the code:
try{
if(!window.openDatabase){
alert('DB not supported.');
}else{
var shortName = 'abc';
var version = '1.0';
var displayName = 'ABC';
var maxSize = 3145728;
var tableName = ['business', 'politic', 'firstread', 'commentary','features', 'insiderasia', 'management', 'media'];
db = openDatabase(shortName, version, displayName, maxSize);
$.each(tableName, function(theCount, value){
db.transaction(
function(transaction){
transaction.executeSql('CREATE TABLE IF NOT EXISTS '+ value +' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, link TEXT NOT NULL, title TEXT NOT NULL, author TEXT NOT NULL, pubdate TEXT NOT NULL, imgLink TEXT NULL, desc TEXT NOT NULL, day TEXT NOT NULL);');
});
});
}
}catch(e){
if(e == INVALID_STATE_ERR){
console.log('invalid database version.');
}else{
console.log('unknown error ' + e + '.');
}
return;
}
For what you need this? If you worry about that you can recreate table that already exist in your database, you need creating your table with this SQL query:
CREATE TABLE IF NOT EXISTS table_name