how can I connect to database - database-connection

I use this but I can't connect DataBase
conn1.Open();
using (OracleCommand crtCommand = new OracleCommand);

for connect to Oracle from application
string command = "Enter your command";
OracleConnection orclecon;
orclecon = new OracleConnection(connection);
orclecon.Open();
use this for select commands:
DataSet ds = new DataSet();
using (OracleDataAdapter Oda = new OracleDataAdapter(command, orclecon))
{
Oda.Fill(ds);
}
and use this for insert/update/delete commands:
//used for Oracle command (insert,update,delete) if number of rows that affected >0 return true else return false
using (OracleCommand orclcommand = new OracleCommand(command, orclecon))
{
int n = orclcommand.ExecuteNonQuery();
if (n > 0)
return true;
else
return false;
}
orclecon.Close();

To make it dynamic use this;
string sentence = "";
string formatprototype = "";//This will hold the string to be formatted.
string output="";
public void SearchString()
{
string pattern = #".*[ ]+?[\""]{1}(?<String>[a-zA-Z0-9_]*)[\""]{1}[ ]+?MINVALUE[ ]*(?<MinValue>[-?\d]*)[ ]*MAXVALUE[ ]*(?<MaxValue>[\d]*)[ ]+?[INCREMENT]*[ ]+?[BY]*[ ]+?(?<IncrementBy>[\d]*)[ ]+?[START]*[ ]+?[WITH]*[ ]+?(?<StartWith>[\d]*)[ ]+?[CACHE]*[ ]+?(?<Cache>[\d]*)\s+?";
Regex regex = new Regex(pattern);
Match match = regex.Match(sentence);
Group #string = match.Groups[1];
Group minvalue = match.Groups[2];
Group maxvalue = match.Groups[3];
Group incrementby = match.Groups[4];
Group startswith = match.Groups[5];
Group cache = match.Groups[6];
formatprototype = #"CREATE SEQUENCE ""{0}"" MINVALUE {1} MAXVALUE {2} INCREMENT BY {3} START WITH {4} CACHE {5} NOORDER NOCYCLE";
if (minvalue.Value.StartsWith("-"))
{
output = string.Format(formatprototype, #string, minvalue, maxvalue, incrementby, maxvalue, cache);
}
else if (!minvalue.Value.StartsWith("-"))
{
output = string.Format(formatprototype, #string, minvalue, maxvalue, incrementby, minvalue, cache);
}
MessageBox.Show(output);
}
Assume that SearchString() is the function in which you are doing this stuff.And make sure to assign each string that is extracted from database,to sentence.Try it and reply if it worked or not.

Related

Optimized approach for Snowfake table search for string/list of strings from Java API

I need to search for string or list of strings Snowflake table using Java API and fetch all the matching rows and display in Angular UI. I am using dynamic SQL (like operator) to generate the query using information schema. I have created this stored procedure and its working. Do we have any better approach or any architectural patterns for this particular usecase.
Based on the search option (starts/ends with) decide the start and end character to be used with Like operator
Get all the varchar,char columns from the table by joining with information schema.
Build dynamic sql with these columns.
Build the json array based on the query result.
CREATE OR REPLACE PROCEDURE SEARCH_DATA(SCHEMA_NAME VARCHAR, TABLE_NAME VARCHAR, SEARCH_OPTION VARCHAR, KEYWORDS ARRAY)
RETURNS VARIANT
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS '
var searchStart = "";
var searchEnd = "";
if (SEARCH_OPTION == "Starts with")
{
searchEnd = "%";
}
else if (SEARCH_OPTION == "Ends with")
{
searchStart = "%";
}
else if (SEARCH_OPTION == "Contains")
{
searchStart = "%";
searchEnd = "%";
}
// Dynamically compose the SQL statement to execute.
var sqlCommand = "select c.column_name from information_schema.COLUMNS c JOIN information_schema.TABLES T ON T.table_name = c.table_name AND T.table_schema = c.table_schema WHERE T.table_schema = ''";
sqlCommand+= SCHEMA_NAME;
sqlCommand+= "'' AND T.table_name= ''";
sqlCommand+= TABLE_NAME;
sqlCommand+= "'' AND c.data_type NOT IN (''TIMESTAMP_TZ'',''BOOLEAN'',''NUMBER'') ORDER BY ordinal_position";
// Prepare statement.
var stmt = snowflake.createStatement({ sqlText: sqlCommand });
// Execute Statement
var rs = stmt.execute();
var columnArray = [];
var columnName = "";
while (rs.next())
{
columnName = rs.getColumnValue(''COLUMN_NAME'');
columnArray.push(columnName);
}
var queryPrefix = "SELECT ''dummy''"
for(var i=0; i< columnArray.length; i++)
{
queryPrefix += "," + columnArray[i];
}
queryPrefix+= " FROM " + SCHEMA_NAME + "." + TABLE_NAME;
var query = "";
for(var j=0; j< KEYWORDS.length; j++)
{
query += queryPrefix;
query += " WHERE (1=0";
for(var i=0; i< columnArray.length; i++)
{
query += " OR "+ columnArray[i] + " LIKE ''" + searchStart + KEYWORDS[j] + searchEnd + "''";
}
query += ")";
if(j < KEYWORDS.length - 1)
query += " UNION ";
}
// Prepare statement.
stmt = snowflake.createStatement({ sqlText: query });
// Execute Statement
rs = stmt.execute();
var resultArray = [];
var row_as_json = {};
while (rs.next())
{
// Put each row in a variable of type JSON.
row_as_json = {};
// For each column in the row...
for (var i=0; i< columnArray.length; i++)
{
row_as_json[columnArray[i]] = rs.getColumnValue(columnArray[i]);
}
// Add the row to the array of rows.
resultArray.push(row_as_json);
}
return resultArray;
';

Joining tables in queries google sheets

Basically I have two google sheets that look something like this:
a table where people can put in their email and select what kind of foo they are using
email
foo
example#email.com
This Foo
and then another table with information about the foo
foo name
foo type
foo boolean1
foo boolean2
This Foo
String
True
True
That Foo
Number
False
True
Other Foo
String
False
False
In a Separate Sheet I'd like to have a dashboard-like view of things wherein I would have counts of various things like number of people, how many of each type of Foo, etc
Where I'm having trouble is figuring out how to pull things like "Number of people who have selected String foos" and such
like, basically i want the google-query equivalent to (in sql)
SELECT COUNT(p.*) FROM people p JOIN info i on p.foo = i.foo_name GROUP BY i.foo_type WHERE i.foo_type = 'String'
What I would be looking for is a table that looks like this:
Data
Count
Active Roster
4
String
3
Number
1
I have also seen many solutions that have complicated formulas using VLOOKUP, INDEX, MATCH, etc.
I decided to write a user function to combine tables, or as I refer to it, de-normalize the database. I wrote the function DENORMALIZE() to support INNER, LEFT, RIGHT and FULL joins. By nesting function calls one can join unlimited tables in theory.
DENORMALIZE(range1, range2, primaryKey, foreignKey, [joinType])
Parameters:
range1, the main table as a named range, a1Notation or an array
range2, the related table as a named range, a1Notation or an array
primaryKey, the unique identifier for the main table, columns start with "1"
foreignKey, the key in the related table to join to the main table, columns start with "1"
joinType, type of join, "Inner", "Left", "Right", "Full", optional and defaults to "Inner", case insensitive
Returns: results as a two dimensional array
Result Set Example:
=QUERY(denormalize("Employees","Orders",1,3), "SELECT * WHERE Col2 = 'Davolio' AND Col8=2", FALSE)
EmpID
LastName
FirstName
OrderID
CustomerID
EmpID
OrderDate
ShipperID
1
Davolio
Nancy
10285
63
1
8/20/1996
2
1
Davolio
Nancy
10292
81
1
8/28/1996
2
1
Davolio
Nancy
10304
80
1
9/12/1996
2
Other Examples:
=denormalize("Employees","Orders",1,3)
=denormalize("Employees","Orders",1,3,"full")
=QUERY(denormalize("Employees","Orders",1,3,"left"), "SELECT * ", FALSE)
=QUERY(denormalize("Employees","Orders",1,3), "SELECT * WHERE Col2 = 'Davolio'", FALSE)
=QUERY(denormalize("Employees","Orders",1,3), "SELECT * WHERE Col2 = 'Davolio' AND Col8=2", FALSE)
=denormalize("Orders","OrderDetails",1,2)
// multiple joins
=denormalize("Employees",denormalize("Orders","OrderDetails",1,2),1,3)
=QUERY(denormalize("Employees",denormalize("Orders","OrderDetails",1,2),1,3), "SELECT *", FALSE)
=denormalize(denormalize("Employees","Orders",1,3),"OrderDetails",1,2)
=QUERY(denormalize("Employees",denormalize("Orders","OrderDetails",1,2),1,3), "SELECT *", FALSE)
=QUERY(denormalize(denormalize("Employees","Orders",1,3),"OrderDetails",4,2), "SELECT *", FALSE)
function denormalize(range1, range2, primaryKey, foreignKey, joinType) {
var i = 0;
var j = 0;
var index = -1;
var lFound = false;
var aDenorm = [];
var hashtable = [];
var aRange1 = "";
var aRange2 = "";
joinType = DefaultTo(joinType, "INNER").toUpperCase();
// the 6 lines below are used for debugging
//range1 = "Employees";
//range1 = "Employees!A2:C12";
//range2 = "Orders";
//primaryKey = 1;
//foreignKey = 3;
//joinType = "LEFT";
// Sheets starts numbering columns starting with "1", arrays are zero-based
primaryKey -= 1;
foreignKey -= 1;
// check if range is not an array
if (typeof range1 !== 'object') {
// Determine if range is a1Notation and load data into an array
if (range1.indexOf(":") !== -1) {
aRange1 = ss.getRange(range1).getValues();
} else {
aRange1 = ss.getRangeByName(range1).getValues();
}
} else {
aRange1 = range1;
}
if (typeof range2 !== 'object') {
if (range2.indexOf(":") !== -1) {
aRange2 = ss.getRange(range2).getValues();
} else {
aRange2 = ss.getRangeByName(range2).getValues();
}
} else {
aRange2 = range2;
}
// make similar structured temp arrays with NULL elements
var tArray1 = MakeArray(aRange1[0].length);
var tArray2 = MakeArray(aRange2[0].length);
var lenRange1 = aRange1.length;
var lenRange2 = aRange2.length;
hashtable = getHT(aRange1, lenRange1, primaryKey);
for(i = 0; i < lenRange2; i++) {
index = hashtable.indexOf(aRange2[i][foreignKey]);
if (index !== -1) {
aDenorm.push(aRange1[index].concat(aRange2[i]));
}
}
// add left and full no matches
if (joinType == "LEFT" || joinType == "FULL") {
for(i = 0; i < lenRange1; i++) {
//index = aDenorm.indexOf(aRange1[i][primaryKey]);
index = aScan(aDenorm, aRange1[i][primaryKey], primaryKey)
if (index == -1) {
aDenorm.push(aRange1[i].concat(tArray2));
}
}
}
// add right and full no matches
if (joinType == "RIGHT" || joinType == "FULL") {
for(i = 0; i < lenRange2; i++) {
index = aScan(aDenorm, aRange2[i][foreignKey], primaryKey)
if (index == -1) {
aDenorm.push(tArray1.concat(aRange2[i]));
}
}
}
return aDenorm;
}
function getHT(aRange, lenRange, key){
var aHashtable = [];
var i = 0;
for (i=0; i < lenRange; i++ ) {
//aHashtable.push([aRange[i][key], i]);
aHashtable.push(aRange[i][key]);
}
return aHashtable;
}
function MakeArray(length) {
var i = 0;
var retArray = [];
for (i=0; i < length; i++) {
retArray.push("");
}
return retArray;
}
function DefaultTo(valueToCheck, valueToDefault) {
return typeof valueToCheck === "undefined" ? valueToDefault : valueToCheck;
}
// Search a multi-dimensional array for a value
function aScan(aValues, searchStr, searchCol) {
var retval = -1;
var i = 0;
var aLen = aValues.length;
for (i = 0; i < aLen; i++) {
if (aValues[i][searchCol] == searchStr) {
retval = i;
break;
}
}
return retval;
}
You can make a copy of the google sheet with data and examples here:
https://docs.google.com/spreadsheets/d/1vziuF8gQcsOxTLEtlcU2cgTAYL1eIaaMTAoIrAS7mnE/edit?usp=sharing

How Create Sequence number in Controller action?

I am working on a project which is an E-health patient Gateway.
I want to generate a number (int type) against a submit form from View to Controller (When phlebotomist receives the blood sample he will check the box and click on submit button). This number is the patient's blood sample number that will be generated in my controller and will be saved in the database. I am using the logic below to create the number but it always gives me zero.
Kindly let me know how I can create numbers one by one in sequence and store in database?
public ActionResult AddSampleTest(int Pid, int Tid, int Stid, string Comment ,string testDate,int DotorID)
{
int sampleNumber=1;
Random rnd = new Random();
int[] sample = new int[50000];
rnd.Next();
for (int ctr = 1; ctr <= sample.Length; ctr++)
{
sampleNumber=sample[ctr + 1];
}
string sampleno = sampleNumber.ToString();
DateTime TestDate = Convert.ToDateTime(testDate);
int Recomended_Test_DoctorID = DotorID;
// Update the Sample Status
PatientTest objpatientTest = db.PatientTests.Where(x => x.PatientID == Pid && x.Testid == Tid && x.SubTestId == Stid && x.Date==TestDate &&x.DoctorId== Recomended_Test_DoctorID).FirstOrDefault();
objpatientTest.SampleStatus = "Sample Received";
objpatientTest.SampleNumber = sampleno;
db.SaveChanges();
var name = User.Identity.Name;
int Lid = db.LabAttendantRecords.Where(x => x.Name == name).Select(x => x.User_id).FirstOrDefault();
LabTestSample obj = new LabTestSample();
obj.labtestid = Tid;
obj.PatientId = Pid;
obj.subtestid = Stid;
obj.labAtendid = Lid;
obj.date = DateTime.Now.Date;
obj.sampleReceived = true;
obj.Comment = sampleno;
db.LabTestSamples.Add(obj);
db.SaveChanges();
return RedirectToAction("TestSampleNumber", "LabAttendantDashboard", new { sampleno});
// Use This for add Result
return RedirectToAction("SubTest", "LabAttendantDashboard", new { Pid, Tid, Stid });
}
sampleNumber is always 0 because each element in sample is 0.
If you want it to be a random number you need to do something like :
Random rnd = new Random();
int sampleNumber = rnd.Next();
string sampleno = sampleNumber.ToString();
If you need to be sure that the sample number is unique, you should use a Guid :
string sampleno = Guid.NewGuid().ToString();

Can not add a list in document object using iTextSharp

public ActionResult PartTimeFacultyCourseLoadReport()
{
var teacherStatistics = (from t in db.Teachers
join c in db.Courses
on t.Id equals c.TeacherId into cGroup
where t.Status == "Part Time"
orderby t.Designation descending
select new
{
TeacherInfo = t,
CourseInfo = from cg in cGroup
orderby cg.Code ascending
select cg
}).ToList();
List<TeacherStatistics> teacherStatisticses = new List<TeacherStatistics>();
int count = 0;
foreach (var teacherStatistic in teacherStatistics)
{
TeacherStatistics aTeacherStatistics = new TeacherStatistics();
aTeacherStatistics.Name = teacherStatistic.TeacherInfo.Name;
aTeacherStatistics.Designation = teacherStatistic.TeacherInfo.Designation;
aTeacherStatistics.NumberOfCourse = teacherStatistic.TeacherInfo.NumberOfCourse;
count = 0;
foreach (var courseInfo in teacherStatistic.CourseInfo)
{
if (count != 0)
{
aTeacherStatistics.Courses += ", ";
}
aTeacherStatistics.Courses += courseInfo.Code;
aTeacherStatistics.Courses += "(";
aTeacherStatistics.Courses += courseInfo.Section;
aTeacherStatistics.Courses += ")";
count++;
}
teacherStatisticses.Add(aTeacherStatistics);
}
var document = new Document(PageSize.A4, 50, 50, 25, 25);
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, output);
document.Open();
var data = teacherStatisticses.ToList();
document.Add(data);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=PartTimeFaculty.pdf");
Response.BinaryWrite(output.ToArray());
document.Close();
return View(teacherStatisticses);
}
I want to pass a list named 'teacherStatisticses' through document object for making a PDF. My code doesn't work. It showed me following Error -
Argument 1: cannot convert from 'System.Collections.Generic.List' to 'iTextSharp.text.IElement'
I assume that you are using some version of itextpdf for the PDF generation.
The error is in the line:
document.Add(data);
There is no way to add plain .NET objects into the PDF document. I can not predict the structure of PDF which you`d like to achieve, but the code mentioned above could be written as:
foreach(var teacher in teacherStatistics)
{
var paragraph = new Paragraph(teacher.ToString()); // instead of teacher.ToString() should be some code which translates teacherStatistics projection to the string representation
document.Add(paragraph);
}
//not tested
A lot of useful samples could be found at
http://developers.itextpdf.com/examples
Basic tutorial for the itextpdf:
http://developers.itextpdf.com/content/itext-7-jump-start-tutorial/chapter-1-introducing-basic-building-blocks

No result with Cypher after batchinserting with indexing

I'm very new to neo4j. I've read this question (Cypher Query not finding Node) but it does not work. I'm getting the error, the the auto_node_index was not found. Perhaps it is because I'm using the BatchInserter?
For my experiment, I'm using neo4j 1.8.2 and the programming language Java with the embedded database.
I want to put some data to the database using the BatchInserter and the BatchInserterIndex like explained on http://docs.neo4j.org/chunked/milestone/batchinsert.html.
BatchInserter myInserter = BatchInserters.inserter(DB_PATH);
BatchInserterIndexProvider indexProvider =
new LuceneBatchInserterIndexProvider( myInserter );
BatchInserterIndex persons =
indexProvider.nodeIndex( "persons", MapUtil.stringMap( "type", "exact" ) );
persons.setCacheCapacity( "name", 10000 );
First I read the data from a TGF-file, create the nodes and put it to the inserter like this:
properties = MapUtil.map("name", actualNodeName, "birthday", birthdayValue);
long node = myInserter.createNode(properties);
nodes.add(node);
persons.flush();
The insert works fine, but when I want to search a node with Cypher, the result is empty
ExecutionEngine engine = new ExecutionEngine( db );
String query =
"start n=node:persons(name='nameToSearch') "
+ " match n-[:KNOWS]->m "
+ " return n.id, m ";
ExecutionResult result = engine.execute( query );
System.out.println(result);
On the other side, when I'm using the Traverser-class and start the search on the rootnode, I receive the nodes wich are connetced by the node with the name "nameToSearch".
Can anybody explain me, why I can't get the nodes with Cypher!
here is the complete method for the batch insert:
public long batchImport() throws IOException{
String actualLine;
ArrayList<Long> nodes = new ArrayList<Long>();
Map<String,Object> properties = new HashMap<String,Object>();
//delete all nodes and edges in the database
FileUtils.deleteRecursively(new File(DB_PATH ));
BatchInserter myInserter = BatchInserters.inserter(DB_PATH);
BatchInserterIndexProvider indexProvider =
new LuceneBatchInserterIndexProvider( myInserter );
BatchInserterIndex persons =
indexProvider.nodeIndex( "persons", MapUtil.stringMap( "type", "exact" ) );
persons.setCacheCapacity( "name", 10000 );
long execTime = 0;
try{
//Get the file which contains the graph informations
FileReader inputFile = new FileReader(UtilFunctions.searchFile(new File(PATH_OUTPUT_MERGED_FILES), "nodesAndEdges").get(0));
LineNumberReader inputLine = new LineNumberReader(inputFile);
// Read nodes up to symbol #
execTime = System.nanoTime();
while ((actualLine=inputLine.readLine()).charAt(0) != '#'){
StringTokenizer myTokenizer = new StringTokenizer(actualLine);
// Read node number
String actualNodeNumber = myTokenizer.nextToken();
// Read node name
String actualNodeName = myTokenizer.nextToken() + " " + myTokenizer.nextToken();
//Read property
myTokenizer.nextToken();
String actualNodePropertyKey = BIRTHDAY_KEY;
String actualNodePropertyValue = myTokenizer.nextToken();
actualNodePropertyValue = actualNodePropertyValue.substring(1, actualNodePropertyValue.length()-1);
// Insert node information
properties = MapUtil.map("name", actualNodeName, "birthday", actualNodePropertyValue, "id", actualNodeNumber);
long node = myInserter.createNode(properties);
nodes.add(node);
persons.flush();
}
// Read edges up to end of file
int countEdges = 0;
while ((actualLine=inputLine.readLine()) != null){
StringTokenizer myTokenizer = new StringTokenizer(actualLine);
// Read start node number
String actualStartNodeNumber = myTokenizer.nextToken();
// Read destination node number
String actualDestinationNodeNumber = myTokenizer.nextToken();
// Read relationship type
String actualRelType = myTokenizer.nextToken();
// Insert node information into ArrayList
int positionStartNode = Integer.parseInt(actualStartNodeNumber);
int positionDestinationNode = Integer.parseInt(actualDestinationNodeNumber);
properties.clear();
if (countEdges == 0) {
myInserter.createRelationship(0, nodes.get(positionStartNode-1), RelType.ROOT, properties);
myInserter.createRelationship(nodes.get(positionStartNode-1), nodes.get(positionDestinationNode-1), RelType.KNOWS, properties);
}
else
{
myInserter.(nodes.get(positionStartNode-1), nodes.get(positionDestinationNode-1), RelType.KNOWS, properties);
}
countEdges++;
}
indexProvider.shutdown();
myInserter.shutdown();
execTime = System.nanoTime() - execTime;
// Close input file
inputLine.close();
inputFile.close();
}
catch (Throwable e){
System.out.println(e.getMessage());
e.printStackTrace();
}
return execTime;
}
Your lacks a call to profiles.add(node, <indexProperties>). Therefore you're never adding anything to the index.
It is crucial that the code using Batchinserter API calls shutdown() on both the BatchInserterIndexProvider and BatchInserter. Maybe you've missed this in your code.
If this does not solve the problem, please post your code.

Resources